diff --git a/.agents/skills/adding-a-trigger/SKILL.md b/.agents/skills/adding-a-trigger/SKILL.md index 8d715cec0b..d68483e62e 100644 --- a/.agents/skills/adding-a-trigger/SKILL.md +++ b/.agents/skills/adding-a-trigger/SKILL.md @@ -79,6 +79,7 @@ Required in `handler_ee.rs`: - `const TABLE_NAME`, `ADDITIONAL_SELECT_FIELDS` - `get_deployed_object`, `validate_config`, `create_trigger`, `update_trigger`, `delete_trigger`, `test_connection` - `additional_routes` (optional — mount extra endpoints for things like ARM resource listing, topic discovery) + - `config_runnables` — required if the config names a script or flow the listener runs (as the WebSocket URL resolver does): it returns them so a save's Hub check sees them. The default returns none, which leaves such a path unchecked. Register the crate in `backend/Cargo.toml` as a workspace member and as a dep of `windmill-api` behind the feature flag. diff --git a/.claude/hooks/lint-frontend.sh b/.claude/hooks/lint-frontend.sh new file mode 100755 index 0000000000..a057e5ffd6 --- /dev/null +++ b/.claude/hooks/lint-frontend.sh @@ -0,0 +1,21 @@ +#!/bin/bash +# Lint a frontend file with oxlint after Claude edits it, and hand any findings back +# as context. Never blocks: the edit stands, Claude sees what to fix. + +INPUT=$(cat) +FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty') +[ -z "$FILE_PATH" ] && exit 0 +[[ "$FILE_PATH" =~ \.(ts|js|svelte)$ ]] || exit 0 + +# Same anchoring as format-frontend.sh: a "frontend" directory at a repo root. +REPO_ROOT="${FILE_PATH%%/frontend/*}" +[[ "$FILE_PATH" == *"/frontend/"* ]] && [[ -e "$REPO_ROOT/.git" ]] || exit 0 +OXLINT="$REPO_ROOT/frontend/node_modules/.bin/oxlint" +[ -x "$OXLINT" ] || exit 0 + +cd "$REPO_ROOT/frontend" || exit 0 +OUT=$("$OXLINT" --format=unix "$FILE_PATH" 2>&1) && exit 0 + +jq -n --arg out "$OUT" '{hookSpecificOutput: {hookEventName: "PostToolUse", + additionalContext: ("oxlint found problems in the file you just edited; fix them:\n" + $out)}}' +exit 0 diff --git a/.claude/settings.json b/.claude/settings.json index 37aaeeb0f5..675336e86f 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -123,6 +123,11 @@ "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-frontend.sh", "timeout": 30 }, + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/lint-frontend.sh", + "timeout": 30 + }, { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-backend.sh", diff --git a/.github/DockerfileBackendTests b/.github/DockerfileBackendTests index 61c853e28a..e61e5d715b 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.13.6/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.8/uv-installer.sh | sh && mv /usr/local/cargo/bin/uv /usr/local/bin/uv ENV TZ=Etc/UTC @@ -42,7 +42,7 @@ RUN wget https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VER RUN /usr/local/bin/python3 -m pip install pip-tools # Bun -COPY --from=oven/bun:1.4.4 /usr/local/bin/bun /usr/bin/bun +COPY --from=oven/bun:1.4.5 /usr/local/bin/bun /usr/bin/bun # Install windmill CLI RUN bun install -g windmill-cli \ diff --git a/.github/actions/sign-attest-image/action.yml b/.github/actions/sign-attest-image/action.yml index 564a621380..f9ee563d1b 100644 --- a/.github/actions/sign-attest-image/action.yml +++ b/.github/actions/sign-attest-image/action.yml @@ -57,7 +57,7 @@ runs: exit 1 - name: SLSA provenance (GitHub artifact attestation) - uses: actions/attest-build-provenance@v4 + uses: actions/attest-build-provenance@v4.2.2 with: subject-name: ${{ inputs.image }} subject-digest: ${{ inputs.digest }} diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0d174a548f..65fa5ccc74 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,11 +11,14 @@ version: 2 updates: - # Maintain dependencies for GitHub Actions + # Maintain dependencies for GitHub Actions (also updates .github/workflows/actions.lock). + # The cooldown lets a compromised release be yanked before we pick it up. - package-ecosystem: "github-actions" - directory: "/" + directories: ["/", "/.github/actions/*"] schedule: interval: "weekly" + cooldown: + default-days: 7 # Maintain dependencies for npm - package-ecosystem: "npm" diff --git a/.github/docker-bake-ee.hcl b/.github/docker-bake-ee.hcl new file mode 100644 index 0000000000..33bb0bc53a --- /dev/null +++ b/.github/docker-bake-ee.hcl @@ -0,0 +1,36 @@ +# EE image and its debug file from one build: both targets share the builder +# stage, so the binary is compiled once and the .gnu_debuglink CRC in the shipped +# binary matches the uploaded debug file. Building them separately recompiles. + +variable "WM_BUILD_VERSION" {} + +variable "SBOM" { + default = "false" +} + +# Tags and labels, filled in by docker/metadata-action's bake files. +target "docker-metadata-action" {} + +target "_ee" { + context = "." + dockerfile = "Dockerfile" + platforms = ["linux/amd64", "linux/arm64"] + args = { + features = "ee" + WM_BUILD_VERSION = WM_BUILD_VERSION + } +} + +target "image" { + inherits = ["_ee", "docker-metadata-action"] + output = ["type=registry"] + attest = SBOM == "true" ? ["type=sbom"] : [] +} + +# Writes ./debuginfo/linux_/windmill.debug. The file names every EE +# function with its source file and line: never push or publish it. +target "debuginfo" { + inherits = ["_ee"] + target = "debuginfo" + output = ["type=local,dest=./debuginfo"] +} diff --git a/.github/mcp-registry/server.json b/.github/mcp-registry/server.json new file mode 100644 index 0000000000..8318250a31 --- /dev/null +++ b/.github/mcp-registry/server.json @@ -0,0 +1,28 @@ +{ + "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", + "name": "io.github.windmill-labs/windmill", + "title": "Windmill", + "description": "Run Windmill scripts and flows and manage jobs, schedules, resources and variables.", + "repository": { + "url": "https://github.com/windmill-labs/windmill", + "source": "github" + }, + "websiteUrl": "https://www.windmill.dev/docs/core_concepts/mcp", + "version": "1.868.0", + "remotes": [ + { + "type": "streamable-http", + "url": "https://app.windmill.dev/api/mcp/gateway" + }, + { + "type": "streamable-http", + "url": "https://{windmill_host}/api/mcp/gateway", + "variables": { + "windmill_host": { + "description": "Host name of your self-hosted Windmill instance, for example windmill.example.com. The server authenticates with OAuth and asks you to pick a workspace.", + "isRequired": true + } + } + } + ] +} diff --git a/.github/scripts/image-vex.sh b/.github/scripts/image-vex.sh new file mode 100755 index 0000000000..d36c09d175 --- /dev/null +++ b/.github/scripts/image-vex.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Writes the OpenVEX document for a release image from its unfiltered Trivy JSON reports. +# +# linux-libc-dev: every CVE found against it is not_affected. It holds only the kernel's userspace +# API headers, which build-essential needs to compile C; a container runs on its host's kernel, so +# a kernel CVE reported against this package never applies to the image. The product carries no +# version or qualifiers so one statement covers every architecture and package version. +# +# setuptools@70.3.0: the copy of pkg_resources pip vendors (pip/_vendor/vendor.txt) in the +# preinstalled Pythons. Only the listed CVEs are covered, each in a setuptools module pip does not +# vendor; a new CVE against that version must be checked before it joins the list. The version is +# pinned so the statements stop applying once pip vendors a different setuptools. +# +# usage: image-vex.sh ... > vex.openvex.json +set -euo pipefail + +id="$1" +shift + +jq -s --arg id "$id" --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" ' + ([.[].Results[]? | (.Vulnerabilities // [])[] | select(.PkgName == "linux-libc-dev") | .VulnerabilityID] + | unique + | map({ + vulnerability: { name: . }, + products: [{ "@id": "pkg:deb/debian/linux-libc-dev" }], + status: "not_affected", + justification: "vulnerable_code_not_present", + impact_statement: "linux-libc-dev contains only the Linux userspace API headers used to compile C code. The image ships no kernel: containers run on the host kernel, which this package does not affect." + })) as $kernel + | ([ + ["CVE-2025-47273", "setuptools.package_index"], + ["CVE-2026-59890", "setuptools.command.sdist and FileList"], + ["GHSA-xmj3-9gf7-h52w", "setuptools.wheel"] + ] + | map({ + vulnerability: { name: .[0] }, + products: [{ "@id": "pkg:pypi/setuptools@70.3.0" }], + status: "not_affected", + justification: "vulnerable_code_not_present", + impact_statement: ("setuptools 70.3.0 is present only as the pkg_resources module pip vendors. The vulnerable code is in " + .[1] + ", which pip does not vendor.") + })) as $pip_setuptools + | { + "@context": "https://openvex.dev/ns/v0.2.0", + "@id": $id, + author: "Windmill Labs", + timestamp: $ts, + version: 1, + statements: ($kernel + $pip_setuptools) + } +' "$@" diff --git a/.github/scripts/kernel-headers-vex.sh b/.github/scripts/kernel-headers-vex.sh deleted file mode 100755 index 3a24c30e1a..0000000000 --- a/.github/scripts/kernel-headers-vex.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash -# Writes an OpenVEX document marking every linux-libc-dev CVE found in the given Trivy JSON -# reports as not_affected. linux-libc-dev holds only the kernel's userspace API headers, which -# build-essential needs to compile C; a container runs on its host's kernel, so a kernel CVE -# reported against this package never applies to the image. The product carries no version or -# qualifiers so one statement covers every architecture and package version. -# -# usage: kernel-headers-vex.sh ... > vex.openvex.json -set -euo pipefail - -id="$1" -shift - -jq -s --arg id "$id" --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" ' - [.[].Results[]? | (.Vulnerabilities // [])[] | select(.PkgName == "linux-libc-dev") | .VulnerabilityID] - | unique - | { - "@context": "https://openvex.dev/ns/v0.2.0", - "@id": $id, - author: "Windmill Labs", - timestamp: $ts, - version: 1, - statements: map({ - vulnerability: { name: . }, - products: [{ "@id": "pkg:deb/debian/linux-libc-dev" }], - status: "not_affected", - justification: "vulnerable_code_not_present", - impact_statement: "linux-libc-dev contains only the Linux userspace API headers used to compile C code. The image ships no kernel: containers run on the host kernel, which this package does not affect." - }) - } -' "$@" diff --git a/.github/workflows/actions-lock.yml b/.github/workflows/actions-lock.yml new file mode 100644 index 0000000000..8e4886b07f --- /dev/null +++ b/.github/workflows/actions-lock.yml @@ -0,0 +1,28 @@ +name: Verify actions lockfile + +on: + push: + branches: [main] + paths: + - ".github/**" + pull_request: + paths: + - ".github/**" + +permissions: {} + +jobs: + verify: + runs-on: ubuntu-latest + permissions: + contents: read + env: + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v4.4.0 + with: + persist-credentials: false + # Bump the extension pin by hand: Dependabot does not track it. + - run: gh extension install github/gh-actions-lock --pin v0.4.1 + # Run `gh actions-lock` locally and commit .github/workflows/actions.lock to fix a failure. + - run: gh actions-lock --verify diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 0000000000..b8edb26ab0 --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,506 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/actions-lock.yml': + - 'actions/checkout@v4.4.0' + '.github/workflows/ai-agent-tests.yml': + - 'actions-rust-lang/setup-rust-toolchain@v1.17.0' + - 'actions/checkout@v4.4.0' + - 'actions/setup-node@v7.1.0' + - 'actions/setup-python@v7.1.0' + - 'actions/upload-artifact@v4.6.2' + - 'oven-sh/setup-bun@v2.2.0' + '.github/workflows/ai-evals-scheduled.yml': + - 'actions-rust-lang/setup-rust-toolchain@v1.17.0' + - 'actions/checkout@v4.4.0' + - 'actions/setup-node@v7.1.0' + - 'actions/upload-artifact@v4.6.2' + - 'oven-sh/setup-bun@v2.2.0' + '.github/workflows/ai-evals-test.yml': + - 'actions-rust-lang/setup-rust-toolchain@v1.17.0' + - 'actions/checkout@v4.4.0' + - 'actions/setup-node@v7.1.0' + - 'actions/upload-artifact@v4.6.2' + - 'oven-sh/setup-bun@v2.2.0' + '.github/workflows/backend-check.yml': + - 'actions-rust-lang/setup-rust-toolchain@v1.17.0' + - 'actions/checkout@v4.4.0' + '.github/workflows/backend-test-windows.yml': + - 'actions-rust-lang/setup-rust-toolchain@v1.17.0' + - 'actions/checkout@v4.4.0' + - 'actions/setup-dotnet@v4.3.1' + - 'actions/setup-go@v7.0.0' + - 'actions/setup-node@v7.1.0' + - 'astral-sh/setup-uv@v10.3.3' + - 'denoland/setup-deno@v2.0.5' + - 'ikalnytskyi/action-setup-postgres@v6' + - 'oven-sh/setup-bun@v2.2.0' + - 'shivammathur/setup-php@2.40.0' + '.github/workflows/backend-test.yml': + - 'actions-rust-lang/setup-rust-toolchain@v1.17.0' + - 'actions/cache@v3.5.0' + - 'actions/checkout@v4.4.0' + - 'actions/setup-dotnet@v4.3.1' + - 'actions/setup-go@v7.0.0' + - 'actions/setup-node@v7.1.0' + - 'astral-sh/setup-uv@v10.3.3' + - 'denoland/setup-deno@v2.0.5' + - 'oven-sh/setup-bun@v2.2.0' + - 'ruby/setup-ruby@v1.338.0' + - 'shivammathur/setup-php@2.40.0' + '.github/workflows/benchmark.yml': + - 'actions/checkout@v4.4.0' + - 'actions/download-artifact@v4.3.0' + - 'actions/upload-artifact@v4.6.2' + - 'denoland/setup-deno@v2.0.5' + '.github/workflows/build-caddy-l4-image.yml': + - 'actions/checkout@v4.4.0' + - 'depot/build-push-action@v1.19.0' + - 'depot/setup-action@v1.7.2' + - 'docker/login-action@v3.7.0' + - 'docker/metadata-action@v5.10.0' + '.github/workflows/build-extra-image.yml': + - 'actions/checkout@v4.4.0' + - 'depot/build-push-action@v1.19.0' + - 'depot/setup-action@v1.7.2' + - 'docker/login-action@v3.7.0' + - 'docker/metadata-action@v5.10.0' + '.github/workflows/build-publish-rh-image.yml': + - 'actions/checkout@v4.4.0' + - 'actions/upload-artifact@v4.6.2' + - 'depot/build-push-action@v1.19.0' + - 'depot/setup-action@v1.7.2' + - 'docker/login-action@v3.7.0' + - 'docker/metadata-action@v5.10.0' + - 'imjasonh/setup-crane@v0.4' + '.github/workflows/build-publish-rh8-image.yml': + - 'actions/checkout@v4.4.0' + - 'actions/upload-artifact@v4.6.2' + - 'depot/build-push-action@v1.19.0' + - 'depot/setup-action@v1.7.2' + - 'docker/login-action@v3.7.0' + - 'docker/metadata-action@v5.10.0' + - 'shrink/actions-docker-extract@v3.1.0' + '.github/workflows/build_cli_image.yml': + - 'actions/attest-build-provenance@v4.2.2' + - 'actions/checkout@v4.4.0' + - 'depot/build-push-action@v1.19.0' + - 'depot/setup-action@v1.7.2' + - 'docker/login-action@v3.7.0' + - 'docker/metadata-action@v5.10.0' + - 'sigstore/cosign-installer@v4.1.2' + '.github/workflows/build_windows_worker_.yml': + - 'actions-rust-lang/setup-rust-toolchain@v1.17.0' + - 'actions/checkout@v4.4.0' + - 'actions/upload-artifact@v4.6.2' + '.github/workflows/change-versions.yml': + - 'actions-rs/toolchain@v1.0.7' + - 'actions/checkout@v4.4.0' + - 'actions/create-github-app-token@v2.2.2' + - 'stefanzweifel/git-auto-commit-action@v5.2.0' + '.github/workflows/check-docs-links.yml': + - 'actions/checkout@v4.4.0' + - 'actions/setup-node@v7.1.0' + '.github/workflows/check-empty-fixture.yml': + - 'actions/checkout@v4.4.0' + '.github/workflows/check-system-prompts.yml': + - 'actions/checkout@v4.4.0' + - 'actions/setup-python@v7.1.0' + '.github/workflows/check-write-access.yml': + - 'actions/create-github-app-token@v2.2.2' + '.github/workflows/claude-plan.yml': + - 'actions/checkout@v4.4.0' + - 'anthropics/claude-code-action@v1.0.271' + '.github/workflows/claude.yml': + - 'actions/checkout@v4.4.0' + - 'anthropics/claude-code-action@v1.0.271' + '.github/workflows/cli-tests.yml': + - 'actions-rust-lang/setup-rust-toolchain@v1.17.0' + - 'actions/checkout@v4.4.0' + - 'actions/setup-node@v7.1.0' + - 'ikalnytskyi/action-setup-postgres@v6' + - 'oven-sh/setup-bun@v2.2.0' + '.github/workflows/codex-pr-review.yml': + - 'actions/checkout@v5.1.0' + - 'actions/github-script@v7.1.0' + - 'actions/setup-node@v7.1.0' + '.github/workflows/discord-notification.yml': [] + '.github/workflows/docker-image-rpi4.yml': + - 'actions/checkout@v4.4.0' + - 'depot/build-push-action@v1.19.0' + - 'depot/setup-action@v1.7.2' + - 'docker/login-action@v3.7.0' + - 'docker/metadata-action@v5.10.0' + '.github/workflows/docker-image.yml': + - 'actions/attest-build-provenance@v4.2.2' + - 'actions/checkout@v4.4.0' + - 'actions/upload-artifact@v4.6.2' + - 'depot/bake-action@v1.13.0' + - 'depot/build-push-action@v1.19.0' + - 'depot/setup-action@v1.7.2' + - 'docker/login-action@v3.7.0' + - 'docker/metadata-action@v5.10.0' + - 'docker/scout-action@v1.28.0' + - 'docker/setup-buildx-action@v2.10.0' + - 'github/codeql-action@v4.39.3' + - 'reggionick/s3-deploy@v4.0.0' + - 'shrink/actions-docker-extract@v3.1.0' + - 'sigstore/cosign-installer@v4.1.2' + - 'softprops/action-gh-release@v2.6.2' + '.github/workflows/frontend-check.yml': + - 'actions/checkout@v4.4.0' + - 'actions/setup-node@v7.1.0' + '.github/workflows/gallery_on_release.yml': + - 'actions/checkout@v4.4.0' + '.github/workflows/git-commands.yaml': + - 'actions-rust-lang/setup-rust-toolchain@v1.17.0' + - 'actions/checkout@v3.7.0' + - 'actions/checkout@v4.4.0' + - 'actions/create-github-app-token@v2.2.2' + - 'actions/github-script@v6.4.1' + - 'anthropics/claude-code-action@beta' + '.github/workflows/git-sync-test.yml': + - 'actions-rust-lang/setup-rust-toolchain@v1.17.0' + - 'actions/checkout@v4.4.0' + - 'actions/setup-node@v7.1.0' + - 'actions/upload-artifact@v4.6.2' + - 'denoland/setup-deno@v2.0.5' + - 'oven-sh/setup-bun@v2.2.0' + '.github/workflows/go_on_release.yml': + - 'actions/checkout@v4.4.0' + - 'actions/setup-go@v7.0.0' + - 'cpina/github-action-push-to-another-repository@v1.7.3' + '.github/workflows/helmchart_on_release.yml': + - 'actions/checkout@v3.7.0' + - 'actions/create-github-app-token@v2.2.2' + '.github/workflows/jsr_on_release.yml': + - 'actions/checkout@v4.4.0' + '.github/workflows/linear-claude.yaml': + - 'actions/checkout@v4.4.0' + - 'anthropics/claude-code-action@beta' + '.github/workflows/npm_on_release.yml': + - 'actions/checkout@v4.4.0' + - 'actions/setup-node@v7.1.0' + - 'oven-sh/setup-bun@v2.2.0' + '.github/workflows/pi-pr-review.yml': + - 'actions/checkout@v5.1.0' + - 'actions/github-script@v7.1.0' + - 'actions/setup-node@v7.1.0' + '.github/workflows/pr-ready-review.yml': + - 'actions/checkout@v5.1.0' + - 'anthropics/claude-code-action@v1.0.271' + '.github/workflows/pr-review-commands.yml': [] + '.github/workflows/publish-cli-docs.yml': + - 'actions/checkout@v4.4.0' + - 'actions/setup-python@v7.1.0' + '.github/workflows/publish-mcp-registry.yml': + - 'actions/checkout@v4.4.0' + - 'sigstore/cosign-installer@v4.1.2' + '.github/workflows/publish_extra.yml': + - 'actions/attest-build-provenance@v4.2.2' + - 'actions/checkout@v4.4.0' + - 'actions/setup-node@v4.4.0' + - 'depot/build-push-action@v1.19.0' + - 'depot/setup-action@v1.7.2' + - 'docker/build-push-action@v7.4.0' + - 'docker/login-action@v3.7.0' + - 'docker/metadata-action@v5.10.0' + - 'docker/setup-buildx-action@v3.12.0' + - 'oven-sh/setup-bun@v2.2.0' + - 'sigstore/cosign-installer@v4.1.2' + '.github/workflows/publish_windows_worker.yml': + - 'actions-rust-lang/setup-rust-toolchain@v1.17.0' + - 'actions/checkout@v4.4.0' + - 'softprops/action-gh-release@v2.6.2' + '.github/workflows/pypi_on_release.yml': + - 'actions/checkout@v4.4.0' + '.github/workflows/refresh-docs-snapshot.yml': + - 'actions/checkout@v4.4.0' + - 'actions/create-github-app-token@v2.2.2' + - 'peter-evans/create-pull-request@v6.1.0' + '.github/workflows/release-please.yml': + - 'googleapis/release-please-action@v5.0.0' + '.github/workflows/rust-client-check.yml': + - 'actions/checkout@v4.4.0' + - 'cachix/install-nix-action@v31.11.5' + '.github/workflows/rust_on_release.yml': + - 'actions/checkout@v4.4.0' + - 'cachix/install-nix-action@v31.11.5' + '.github/workflows/sdk-tests.yml': + - 'actions/checkout@v4.4.0' + - 'actions/setup-node@v7.1.0' + - 'astral-sh/setup-uv@v10.3.3' + - 'oven-sh/setup-bun@v2.2.0' + '.github/workflows/shareable-discord-notification.yml': [] + '.github/workflows/sign-cla.yml': + - 'contributor-assistant/github-action@v2.6.1' + '.github/workflows/validate-openapi.yml': + - 'actions/checkout@v4.4.0' + - 'actions/setup-node@v7.1.0' + '.github/workflows/weekly-pr-summary.yml': + - 'actions/checkout@v4.4.0' + - 'anthropics/claude-code-action@v1.0.271' + '.github/workflows/yaml-validator-tests.yml': + - 'actions/checkout@v4.4.0' + - 'actions/setup-node@v7.1.0' +dependencies: + 'actions-rs/toolchain@v1.0.7': + ref: 'v1.0.7' + commit: 'sha1-16499b5e05bf2e26879000db0c1d13f7e13fa3af' + owner_id: 55226457 + repo_id: 208060770 + 'actions-rust-lang/setup-rust-toolchain@v1.17.0': + ref: 'v1.17.0' + commit: 'sha1-166cdcfd11aee3cb47222f9ddb555ce30ddb9659' + owner_id: 103899579 + repo_id: 482610590 + uses: + - 'swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4' + 'actions/attest-build-provenance@v4.2.2': + ref: 'v4.2.2' + commit: 'sha1-4d101475d8b20a2381f78447822ac1eab6504dd8' + owner_id: 44036562 + repo_id: 760702757 + uses: + - 'actions/attest@508db95dd578ae2727ebd6217d5ba78e4fbda05d' + 'actions/attest@508db95dd578ae2727ebd6217d5ba78e4fbda05d': + ref: 'v4.2.1' + commit: 'sha1-508db95dd578ae2727ebd6217d5ba78e4fbda05d' + owner_id: 44036562 + repo_id: 760701061 + 'actions/cache@v3.5.0': + ref: 'v3.5.0' + commit: 'sha1-6f8efc29b200d32929f49075959781ed54ec270c' + owner_id: 44036562 + repo_id: 215566462 + 'actions/checkout@v3.7.0': + ref: 'v3.7.0' + commit: 'sha1-a37ce9120846195fa4ece8f58b268e6043cb2f26' + owner_id: 44036562 + repo_id: 197814629 + 'actions/checkout@v4.4.0': + ref: 'v4.4.0' + commit: 'sha1-11d5960a326750d5838078e36cf38b85af677262' + owner_id: 44036562 + repo_id: 197814629 + 'actions/checkout@v5.1.0': + ref: 'v5.1.0' + commit: 'sha1-fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + owner_id: 44036562 + repo_id: 197814629 + 'actions/create-github-app-token@v2.2.2': + ref: 'v2.2.2' + commit: 'sha1-fee1f7d63c2ff003460e3d139729b119787bc349' + owner_id: 44036562 + repo_id: 642580244 + 'actions/download-artifact@v4.3.0': + ref: 'v4.3.0' + commit: 'sha1-d3f86a106a0bac45b974a628896c90dbdf5c8093' + owner_id: 44036562 + repo_id: 192626254 + 'actions/github-script@v6.4.1': + ref: 'v6.4.1' + commit: 'sha1-d7906e4ad0b1822421a7e6a35d5ca353c962f410' + owner_id: 44036562 + repo_id: 205262760 + 'actions/github-script@v7.1.0': + ref: 'v7.1.0' + commit: 'sha1-f28e40c7f34bde8b3046d885e986cb6290c5673b' + owner_id: 44036562 + repo_id: 205262760 + 'actions/setup-dotnet@v4.3.1': + ref: 'v4.3.1' + commit: 'sha1-67a3573c9a986a3f9c594539f4ab511d57bb3ce9' + owner_id: 44036562 + repo_id: 192625306 + 'actions/setup-go@v7.0.0': + ref: 'v7.0.0' + commit: 'sha1-b7ad1dad31e06c5925ef5d2fc7ad053ef454303e' + owner_id: 44036562 + repo_id: 192624594 + 'actions/setup-node@v4.4.0': + ref: 'v4.4.0' + commit: 'sha1-49933ea5288caeca8642d1e84afbd3f7d6820020' + owner_id: 44036562 + repo_id: 189476904 + 'actions/setup-node@v7.1.0': + ref: 'v7.1.0' + commit: 'sha1-949feb2413d6458794dcd2491c4babbbce0c15c1' + owner_id: 44036562 + repo_id: 189476904 + 'actions/setup-python@v7.1.0': + ref: 'v7.1.0' + commit: 'sha1-6d4fd22b20465ccc0f7354476588e8df7c9ca0e0' + owner_id: 44036562 + repo_id: 192625525 + 'actions/upload-artifact@v4.6.2': + ref: 'v4.6.2' + commit: 'sha1-ea165f8d65b6e75b540449e92b4886f43607fa02' + owner_id: 44036562 + repo_id: 192625955 + 'anthropics/claude-code-action@beta': + ref: 'beta' + commit: 'sha1-28f83620103c48a57093dcc2837eec89e036bb9f' + owner_id: 76263028 + repo_id: 986421638 + uses: + - 'oven-sh/setup-bun@735343b667d3e6f658f44d0eca948eb6282f2b76' + 'anthropics/claude-code-action@v1.0.271': + ref: 'v1.0.271' + commit: 'sha1-4fa93a88de49bbef68b10eb15aabedf28ca0e1ed' + owner_id: 76263028 + repo_id: 986421638 + uses: + - 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6' + 'astral-sh/setup-uv@v10.3.3': + ref: 'v10.3.3' + commit: 'sha1-68559e99cc807c1eb7e9238fd43a15bba460eec2' + owner_id: 115962839 + repo_id: 846733598 + 'cachix/install-nix-action@v31.11.5': + ref: 'v31.11.5' + commit: 'sha1-3dc140bfc76c49fbd4dd958429132e3746bcb086' + owner_id: 36824654 + repo_id: 212301524 + 'contributor-assistant/github-action@v2.6.1': + ref: 'v2.6.1' + commit: 'sha1-ca4a40a7d1004f18d9960b404b97e5f30a505a08' + owner_id: 83762583 + repo_id: 233005322 + 'cpina/github-action-push-to-another-repository@v1.7.3': + ref: 'v1.7.3' + commit: 'sha1-55306faa4ed53b815ae49e564af8cfb359d32ae2' + owner_id: 489071 + repo_id: 251053788 + 'denoland/setup-deno@v2.0.5': + ref: 'v2.0.5' + commit: 'sha1-22d081ff2d3a40755e97629de92e3bcbfa7cf2ed' + owner_id: 42048915 + repo_id: 356423100 + 'depot/bake-action@v1.13.0': + ref: 'v1.13.0' + commit: 'sha1-1d58c2668346981089b088b7ef36755b206b20e9' + owner_id: 68166601 + repo_id: 592294255 + 'depot/build-push-action@v1.19.0': + ref: 'v1.19.0' + commit: 'sha1-0f27be7c41d76663a98518dfe68f1c46582242c4' + owner_id: 68166601 + repo_id: 496245433 + 'depot/setup-action@v1.7.2': + ref: 'v1.7.2' + commit: 'sha1-91bc8495a33ebfc504ffc89e5674379ccf23c29c' + owner_id: 68166601 + repo_id: 471762060 + 'docker/build-push-action@v7.4.0': + ref: 'v7.4.0' + commit: 'sha1-c3c9e263c25d99ce0380d002d59b67737d91b0dc' + owner_id: 5429470 + repo_id: 241092383 + 'docker/login-action@v3.7.0': + ref: 'v3.7.0' + commit: 'sha1-c94ce9fb468520275223c153574b00df6fe4bcc9' + owner_id: 5429470 + repo_id: 287743349 + 'docker/metadata-action@v5.10.0': + ref: 'v5.10.0' + commit: 'sha1-c299e40c65443455700f0fdfc63efafe5b349051' + owner_id: 5429470 + repo_id: 306769011 + 'docker/scout-action@v1.28.0': + ref: 'v1.28.0' + commit: 'sha1-4bbf17a9da65a7b5497361bb407e88cc9548f69c' + owner_id: 5429470 + repo_id: 607129616 + 'docker/setup-buildx-action@v2.10.0': + ref: 'v2.10.0' + commit: 'sha1-885d1462b80bc1c1c7f0b00334ad271f09369c55' + owner_id: 5429470 + repo_id: 288485773 + 'docker/setup-buildx-action@v3.12.0': + ref: 'v3.12.0' + commit: 'sha1-8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + owner_id: 5429470 + repo_id: 288485773 + 'github/codeql-action@v4.39.3': + ref: 'v4.39.3' + commit: 'sha1-33d7b85da1a04171e211befe2c739303b9a4c066' + owner_id: 9919 + repo_id: 259445878 + 'googleapis/release-please-action@v5.0.0': + ref: 'v5.0.0' + commit: 'sha1-45996ed1f6d02564a971a2fa1b5860e934307cf7' + owner_id: 16785467 + repo_id: 262236530 + 'ikalnytskyi/action-setup-postgres@v6': + ref: 'v6' + commit: 'sha1-687404e7b78b0b3471751635e69f70d54a09d6e7' + owner_id: 166626 + repo_id: 430889572 + 'imjasonh/setup-crane@v0.4': + ref: 'v0.4' + commit: 'sha1-31b88efe9de28ae0ffa220711af4b60be9435f6e' + owner_id: 210737 + repo_id: 388840211 + 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6': + ref: 'v2.2.0' + commit: 'sha1-0c5077e51419868618aeaa5fe8019c62421857d6' + owner_id: 108928776 + repo_id: 512644635 + 'oven-sh/setup-bun@735343b667d3e6f658f44d0eca948eb6282f2b76': + ref: 'v2.0.2' + commit: 'sha1-735343b667d3e6f658f44d0eca948eb6282f2b76' + owner_id: 108928776 + repo_id: 512644635 + 'oven-sh/setup-bun@v2.2.0': + ref: 'v2.2.0' + commit: 'sha1-0c5077e51419868618aeaa5fe8019c62421857d6' + owner_id: 108928776 + repo_id: 512644635 + 'peter-evans/create-pull-request@v6.1.0': + ref: 'v6.1.0' + commit: 'sha1-c5a7806660adbe173f04e3e038b0ccdcd758773c' + owner_id: 18365890 + repo_id: 197176365 + 'reggionick/s3-deploy@v4.0.0': + ref: 'v4.0.0' + commit: 'sha1-04c48f45adfd7a34c66348cf9cd1b6cd117cc467' + owner_id: 4193249 + repo_id: 254439900 + 'ruby/setup-ruby@v1.338.0': + ref: 'v1.338.0' + commit: 'sha1-b3aaceaef7e0ee231b499e7b5f49c03fc1d32199' + owner_id: 210414 + repo_id: 231208785 + 'shivammathur/setup-php@2.40.0': + ref: '2.40.0' + commit: 'sha1-eb7c497e18156a6bbabfef1d3a82760b9eda3962' + owner_id: 1571086 + repo_id: 206578964 + 'shrink/actions-docker-extract@v3.1.0': + ref: 'v3.1.0' + commit: 'sha1-04c17c51a5b9fd93b7aed2e05e86c8fe2d90ee52' + owner_id: 349689 + repo_id: 291294922 + 'sigstore/cosign-installer@v4.1.2': + ref: 'v4.1.2' + commit: 'sha1-6f9f17788090df1f26f669e9d70d6ae9567deba6' + owner_id: 71096353 + repo_id: 351211695 + 'softprops/action-gh-release@v2.6.2': + ref: 'v2.6.2' + commit: 'sha1-3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + owner_id: 2242 + repo_id: 204253808 + 'stefanzweifel/git-auto-commit-action@v5.2.0': + ref: 'v5.2.0' + commit: 'sha1-b863ae1933cb653a53c021fe36dbb774e1fb9403' + owner_id: 1080923 + repo_id: 191163758 + 'swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4': + ref: 'v2.9.1' + commit: 'sha1-c19371144df3bb44fab255c43d04cbc2ab54d1c4' + owner_id: 580492 + repo_id: 298565987 diff --git a/.github/workflows/ai-agent-tests.yml b/.github/workflows/ai-agent-tests.yml index 255f07e253..5d233b523b 100644 --- a/.github/workflows/ai-agent-tests.yml +++ b/.github/workflows/ai-agent-tests.yml @@ -52,22 +52,22 @@ jobs: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache-workspaces: backend toolchain: 1.97.0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@v2.2.0 with: - bun-version: 1.4.4 + bun-version: 1.4.5 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@v7.1.0 with: node-version: "20" - - uses: actions/setup-python@v7 + - uses: actions/setup-python@v7.1.0 with: python-version: "3.11" @@ -125,7 +125,7 @@ jobs: --ignore=test_image_output.py - name: Archive Windmill logs - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v4.6.2 if: always() with: name: ai-agent-tests-windmill-logs diff --git a/.github/workflows/ai-evals-scheduled.yml b/.github/workflows/ai-evals-scheduled.yml index f92a90bae5..c4e7700ac6 100644 --- a/.github/workflows/ai-evals-scheduled.yml +++ b/.github/workflows/ai-evals-scheduled.yml @@ -40,13 +40,13 @@ jobs: outputs: matrix: ${{ steps.matrix.outputs.matrix }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: sparse-checkout: ai_evals/core - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@v2.2.0 with: - bun-version: 1.4.4 + bun-version: 1.4.5 - id: matrix env: @@ -84,18 +84,18 @@ jobs: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache-workspaces: backend toolchain: 1.97.0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@v2.2.0 with: - bun-version: 1.4.4 + bun-version: 1.4.5 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@v7.1.0 with: node-version: "24" @@ -188,7 +188,7 @@ jobs: done - name: Archive logs and results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v4.6.2 if: always() with: name: ai-evals-${{ matrix.mode }}-${{ matrix.model }} diff --git a/.github/workflows/ai-evals-test.yml b/.github/workflows/ai-evals-test.yml index a34271ad17..6f7d1877b3 100644 --- a/.github/workflows/ai-evals-test.yml +++ b/.github/workflows/ai-evals-test.yml @@ -69,18 +69,18 @@ jobs: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache-workspaces: backend toolchain: 1.97.0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@v2.2.0 with: - bun-version: 1.4.4 + bun-version: 1.4.5 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@v7.1.0 with: # Node 24 ships npm 11, which frontend/package-lock.json is authored # with; npm 10 rejects it ("Missing: picomatch@4.0.5 from lock file"). @@ -181,7 +181,7 @@ jobs: [ "$fail" = 0 ] || { echo "ai_evals global smoke failed"; exit 1; } - name: Archive logs and results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v4.6.2 if: always() with: name: ai-evals-global-logs diff --git a/.github/workflows/backend-check.yml b/.github/workflows/backend-check.yml index 752ca3baa2..a170feff16 100644 --- a/.github/workflows/backend-check.yml +++ b/.github/workflows/backend-check.yml @@ -13,14 +13,14 @@ jobs: check_oss: runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: fetch-depth: 0 - name: Install mold and clang run: sudo apt-get update && sudo apt-get install -y mold clang - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache: false toolchain: 1.97.0 @@ -32,7 +32,7 @@ jobs: check_oss_full: runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: fetch-depth: 0 @@ -41,7 +41,7 @@ jobs: sudo apt-get update sudo apt-get install -y libxml2-dev libxmlsec1-dev libkrb5-dev libsasl2-dev libcurl4-openssl-dev mold clang - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache: false toolchain: 1.97.0 @@ -55,7 +55,7 @@ jobs: check_ee: runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: fetch-depth: 0 @@ -63,7 +63,7 @@ jobs: run: | echo "ee_repo_ref=$(cat ./backend/ee-repo-ref.txt)" >> "$GITHUB_ENV" - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -78,7 +78,7 @@ jobs: - name: Install mold and clang run: sudo apt-get update && sudo apt-get install -y mold clang - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache: false toolchain: 1.97.0 @@ -90,7 +90,7 @@ jobs: check_ee_full: runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: fetch-depth: 0 @@ -98,7 +98,7 @@ jobs: run: | echo "ee_repo_ref=$(cat ./backend/ee-repo-ref.txt)" >> "$GITHUB_ENV" - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -115,7 +115,7 @@ jobs: run: | ./backend/substitute_ee_code.sh --copy --dir ./windmill-ee-private - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache-workspaces: backend toolchain: 1.97.0 diff --git a/.github/workflows/backend-test-windows.yml b/.github/workflows/backend-test-windows.yml index e4eae57454..79e46244e2 100644 --- a/.github/workflows/backend-test-windows.yml +++ b/.github/workflows/backend-test-windows.yml @@ -17,7 +17,7 @@ jobs: cargo_test_windows: runs-on: blacksmith-16vcpu-windows-2025 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - name: Read EE repo commit hash shell: pwsh @@ -26,7 +26,7 @@ jobs: echo "ee_repo_ref=$ee_repo_ref" | Out-File -FilePath $env:GITHUB_ENV -Append - name: Checkout windmill-ee-private repository - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -47,7 +47,7 @@ jobs: database: windmill port: 5432 - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache-workspaces: backend toolchain: 1.97.0 @@ -57,33 +57,33 @@ jobs: # and the build_windows_worker_ release build, not this test job. rustflags: "" - - uses: actions/setup-dotnet@v4 + - uses: actions/setup-dotnet@v4.3.1 with: dotnet-version: "9.0.x" - - uses: denoland/setup-deno@v2 + - uses: denoland/setup-deno@v2.0.5 with: # 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 + - uses: actions/setup-go@v7.0.0 with: go-version: 1.21.5 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@v2.2.0 with: - bun-version: 1.4.4 + bun-version: 1.4.5 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@v7.1.0 with: node-version: "20" - - uses: astral-sh/setup-uv@v7 + - uses: astral-sh/setup-uv@v10.3.3 with: - version: "0.13.6" + version: "0.13.8" - - uses: shivammathur/setup-php@v2 + - uses: shivammathur/setup-php@2.40.0 with: php-version: "8.3" tools: composer diff --git a/.github/workflows/backend-test.yml b/.github/workflows/backend-test.yml index bb579919ef..36cb3abc6f 100644 --- a/.github/workflows/backend-test.yml +++ b/.github/workflows/backend-test.yml @@ -44,32 +44,32 @@ jobs: --health-cmd "mysqladmin ping -h localhost" --health-interval 10s --health-timeout 5s --health-retries 5 steps: - - uses: actions/checkout@v4 - - uses: actions/setup-dotnet@v4 + - uses: actions/checkout@v4.4.0 + - uses: actions/setup-dotnet@v4.3.1 with: dotnet-version: "9.0.x" - - uses: denoland/setup-deno@v2 + - uses: denoland/setup-deno@v2.0.5 with: # 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 + - uses: actions/setup-go@v7.0.0 with: go-version: 1.21.5 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@v2.2.0 with: - bun-version: 1.4.4 - - uses: actions/setup-node@v7 + bun-version: 1.4.5 + - uses: actions/setup-node@v7.1.0 with: node-version: "24" - - uses: astral-sh/setup-uv@v7 + - uses: astral-sh/setup-uv@v10.3.3 with: - version: "0.13.6" - - uses: shivammathur/setup-php@v2 + version: "0.13.8" + - uses: shivammathur/setup-php@2.40.0 with: php-version: "8.3" tools: composer - - uses: ruby/setup-ruby@v1 + - uses: ruby/setup-ruby@v1.338.0 with: ruby-version: "3.3" bundler-cache: false @@ -94,10 +94,16 @@ jobs: echo "$PG_BIN" >> "$GITHUB_PATH" "$PG_BIN/pg_dump" --version working-directory: / - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache-workspaces: backend toolchain: 1.97.0 + # ubicloud's cache is not scoped per branch, so a PR's save is restored by main and every + # other PR. Each save keeps the artifacts it restored, so PR saves grew the cache from + # ~2GB to ~8GB compressed and the restored target dir filled the runner's disk at link + # time. Save from main only; bump cache-key to drop a bloated cache. + cache-key: v2 + cache-save-if: ${{ github.ref == 'refs/heads/main' }} - name: Fix stale v8 build cache working-directory: ./backend run: | @@ -114,7 +120,7 @@ jobs: run: | echo "ee_repo_ref=$(cat ./ee-repo-ref.txt)" >> "$GITHUB_ENV" - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -237,15 +243,17 @@ jobs: fi echo "Verified: Package requires authentication for @windmill-test/private-pkg" - name: Cache DuckDB FFI module build - uses: actions/cache@v3 + uses: actions/cache@v3.5.0 with: path: ./backend/windmill-duckdb-ffi-internal/target key: ${{ runner.os }}-duckdb-ffi-${{ hashFiles('./backend/windmill-duckdb-ffi-internal/src/**/*.rs', './backend/windmill-duckdb-ffi-internal/Cargo.toml', './backend/windmill-duckdb-ffi-internal/Cargo.lock') }} restore-keys: | ${{ runner.os }}-duckdb-ffi- - - name: cargo test + - name: cargo test (build) timeout-minutes: 30 - env: + # Shared with the run step below: any difference in RUSTFLAGS or the + # CARGO_* settings changes cargo's fingerprints and rebuilds everything there. + env: &cargo_test_env # setup-rust-toolchain exports RUSTFLAGS=-D warnings, and the RUSTFLAGS env # var fully REPLACES (never merges with) target.*.rustflags in # backend/.cargo/config.toml. That silently drops the config's @@ -296,10 +304,16 @@ jobs: WMDEBUG_FORCE_RUNNABLE_SETTINGS_V0: 1 WMDEBUG_FORCE_NO_LEGACY_DEBOUNCING_COMPAT: 1 TEST_NPM_REGISTRY: "http://localhost:4873/:_authToken=${{ env.NPM_TOKEN }}" + WM_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 run: | deno --version && bun -v && node --version && go version && python3 --version && php --version && ruby --version && pwsh --version && dotnet --version # The FFI crate is excluded from the workspace, so the `cargo test` below # 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,openidconnect --all -- --nocapture --test-threads=10 + cargo test --features "$WM_TEST_FEATURES" --all --no-run + - name: cargo test (run) + timeout-minutes: 20 + env: *cargo_test_env + run: | + 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 "$WM_TEST_FEATURES" --all -- --nocapture --test-threads=10 diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index 475d7860d8..61d584aa23 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -35,7 +35,7 @@ jobs: ports: - 8000:8000 steps: - - uses: denoland/setup-deno@v2 + - uses: denoland/setup-deno@v2.0.5 with: deno-version: v2.x - name: benchmark @@ -45,7 +45,7 @@ jobs: -c https://raw.githubusercontent.com/windmill-labs/windmill/${GITHUB_REF##ref/head/}/benchmarks/suite_config.json - name: Save benchmark results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v4.6.2 with: name: benchmark_single path: | @@ -77,7 +77,7 @@ jobs: ports: - 8000:8000 steps: - - uses: denoland/setup-deno@v2 + - uses: denoland/setup-deno@v2.0.5 with: deno-version: v2.x - name: benchmark @@ -87,7 +87,7 @@ jobs: --no-warm-up -c https://raw.githubusercontent.com/windmill-labs/windmill/${GITHUB_REF##ref/head/}/benchmarks/suite_dedicated.json - name: Save benchmark results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v4.6.2 with: name: benchmark_dedicated path: | @@ -152,7 +152,7 @@ jobs: --pull always steps: - - uses: denoland/setup-deno@v2 + - uses: denoland/setup-deno@v2.0.5 with: deno-version: v2.x - name: benchmark @@ -164,7 +164,7 @@ jobs: --workers 4 --factor 3 - name: Save benchmark results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v4.6.2 with: name: benchmark_4workers path: | @@ -272,7 +272,7 @@ jobs: options: >- --pull always steps: - - uses: denoland/setup-deno@v2 + - uses: denoland/setup-deno@v2.0.5 with: deno-version: v2.x - name: benchmark @@ -284,7 +284,7 @@ jobs: --workers 8 --factor 3 - name: Save benchmark results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v4.6.2 with: name: benchmark_8workers path: | @@ -317,7 +317,7 @@ jobs: ports: - 8000:8000 steps: - - uses: denoland/setup-deno@v2 + - uses: denoland/setup-deno@v2.0.5 with: deno-version: v2.x - name: benchmark @@ -327,7 +327,7 @@ jobs: -c https://raw.githubusercontent.com/windmill-labs/windmill/${GITHUB_REF##ref/head/}/benchmarks/suite_wac.json - name: Save benchmark results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v4.6.2 with: name: benchmark_wac path: | @@ -342,14 +342,14 @@ jobs: - benchmark_8workers - benchmark_wac steps: - - uses: denoland/setup-deno@v2 + - uses: denoland/setup-deno@v2.0.5 with: deno-version: v2.x - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: ref: benchmarks - name: Download benchmark results - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v4.3.0 with: merge-multiple: true - name: graphs diff --git a/.github/workflows/build-caddy-l4-image.yml b/.github/workflows/build-caddy-l4-image.yml index a26f1df2cc..4e9ec3ae80 100644 --- a/.github/workflows/build-caddy-l4-image.yml +++ b/.github/workflows/build-caddy-l4-image.yml @@ -26,8 +26,8 @@ jobs: build_ee: runs-on: ubicloud steps: - - uses: actions/checkout@v4 - - uses: depot/setup-action@v1 + - uses: actions/checkout@v4.4.0 + - uses: depot/setup-action@v1.7.2 # docker-compose.yml pins an exact tag, and the Caddyfile it must agree # with lives in the same checkout. Fail the build rather than publish a @@ -59,7 +59,7 @@ jobs: - name: Docker meta id: meta-ee-public - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} @@ -83,14 +83,14 @@ jobs: docker/test-caddy-compat.sh caddy-l4:ci - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Build and push publicly - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: ./docker file: ./docker/DockerfileCaddyL4 diff --git a/.github/workflows/build-extra-image.yml b/.github/workflows/build-extra-image.yml index d1b404b75d..f8030aa2c2 100644 --- a/.github/workflows/build-extra-image.yml +++ b/.github/workflows/build-extra-image.yml @@ -26,16 +26,16 @@ jobs: build_extra: runs-on: ubicloud steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: ref: ${{ github.ref }} fetch-depth: 0 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Docker meta id: meta - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-extra @@ -46,14 +46,14 @@ jobs: type=sha,enable=true,priority=100,prefix=,suffix=,format=short - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Build and push - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: . platforms: linux/amd64,linux/arm64 diff --git a/.github/workflows/build-publish-rh-image.yml b/.github/workflows/build-publish-rh-image.yml index f037e7eb75..448d3ecae1 100644 --- a/.github/workflows/build-publish-rh-image.yml +++ b/.github/workflows/build-publish-rh-image.yml @@ -11,7 +11,7 @@ jobs: build_ee: runs-on: ubicloud-standard-4 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: fetch-depth: 0 @@ -19,7 +19,7 @@ jobs: run: | echo "ee_repo_ref=$(cat ./backend/ee-repo-ref.txt)" >> "$GITHUB_ENV" - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -27,11 +27,11 @@ jobs: token: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }} fetch-depth: 0 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Docker meta id: meta-ee-public - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee-rhel9 @@ -41,7 +41,7 @@ jobs: type=sha - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -56,7 +56,7 @@ jobs: cp ./docker/RHEL9/Dockerfile ./Dockerfile - name: Build and push EE (multi-arch) - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: . platforms: linux/amd64,linux/arm64 @@ -96,22 +96,22 @@ jobs: cp /tmp/amd64/usr/src/app/windmill_duckdb_runner extracted/windmill_duckdb_runner-amd64 rm -rf /tmp/amd64 - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v4.6.2 with: name: RHEL9-arm64 build path: extracted/windmill-ee-arm64-rhel9 - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v4.6.2 with: name: RHEL9-amd64 build path: extracted/windmill-ee-amd64-rhel9 - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v4.6.2 with: name: RHEL9-arm64 dynamic libraries build path: extracted/windmill_duckdb_runner-arm64 - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v4.6.2 with: name: RHEL9-amd64 dynamic libraries build 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 83b12d3290..5d21c9e07b 100644 --- a/.github/workflows/build-publish-rh8-image.yml +++ b/.github/workflows/build-publish-rh8-image.yml @@ -11,7 +11,7 @@ jobs: build_ee: runs-on: ubicloud-standard-4 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: fetch-depth: 0 @@ -19,7 +19,7 @@ jobs: run: | echo "ee_repo_ref=$(cat ./backend/ee-repo-ref.txt)" >> "$GITHUB_ENV" - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -29,11 +29,11 @@ jobs: # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Docker meta id: meta-ee-public - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee-rhel8 @@ -43,7 +43,7 @@ jobs: type=sha - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -58,7 +58,7 @@ jobs: cp ./docker/RHEL8/Dockerfile ./Dockerfile - name: Build and push publicly ee amd64 - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: . platforms: linux/amd64 @@ -76,7 +76,7 @@ jobs: org.opencontainers.image.licenses=Windmill-Enterprise-License - name: Build and push publicly ee arm64 - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: . platforms: linux/arm64 @@ -93,13 +93,13 @@ jobs: ${{ steps.meta-ee-public.outputs.labels }}-arm64 org.opencontainers.image.licenses=Windmill-Enterprise-License - - uses: shrink/actions-docker-extract@v3 + - uses: shrink/actions-docker-extract@v3.1.0 id: extract-ee-amd64 with: image: ${{ steps.meta-ee-public.outputs.tags}}-amd64 path: "/windmill/target/release/windmill" - - uses: shrink/actions-docker-extract@v3 + - uses: shrink/actions-docker-extract@v3.1.0 id: extract-duckdb-ffi-internal with: image: ${{ steps.meta-ee-public.outputs.tags}}-amd64 @@ -116,12 +116,12 @@ jobs: mv "${{ steps.extract-ee-amd64.outputs.destination }}/windmill" "${{ steps.extract-ee-amd64.outputs.destination }}/windmill-ee-amd64-rhel8" # mv "${{ steps.extract-ee-arm64.outputs.destination }}/windmill" "${{ steps.extract-ee-arm64.outputs.destination }}/windmill-ee-arm64-rhel8" - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v4.6.2 with: name: RHEL8-amd64 build path: ${{ steps.extract-ee-amd64.outputs.destination }}/windmill-ee-amd64-rhel8 - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v4.6.2 with: name: RHEL8-amd64 dynamic libraries build path: ${{ steps.extract-duckdb-ffi-internal.outputs.destination }}/windmill_duckdb_runner diff --git a/.github/workflows/build_cli_image.yml b/.github/workflows/build_cli_image.yml index de64a76583..a3806aa45d 100644 --- a/.github/workflows/build_cli_image.yml +++ b/.github/workflows/build_cli_image.yml @@ -22,13 +22,13 @@ jobs: if: github.event_name == 'push' || !startsWith(github.ref, 'refs/tags/') runs-on: ubicloud steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: fetch-depth: 0 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Docker meta id: meta - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} @@ -39,7 +39,7 @@ jobs: type=semver,pattern={{major}}.{{minor}} - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -47,7 +47,7 @@ jobs: - name: Build and push publicly id: docker_build - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: file: "./docker/DockerfileCli" platforms: linux/amd64,linux/arm64 @@ -62,7 +62,7 @@ jobs: - name: Sign and attest release image if: startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' - uses: ./.github/actions/sign-attest-image + uses: $/.github/actions/sign-attest-image with: image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} digest: ${{ steps.docker_build.outputs.digest }} diff --git a/.github/workflows/build_windows_worker_.yml b/.github/workflows/build_windows_worker_.yml index 4a6368ee1e..cf89e4baa2 100644 --- a/.github/workflows/build_windows_worker_.yml +++ b/.github/workflows/build_windows_worker_.yml @@ -13,7 +13,7 @@ jobs: cargo_build_windows: runs-on: blacksmith-16vcpu-windows-2025 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - name: Read EE repo commit hash shell: pwsh @@ -22,7 +22,7 @@ jobs: echo "ee_repo_ref=$ee_repo_ref" | Out-File -FilePath $env:GITHUB_ENV -Append - name: Checkout windmill-ee-private repository - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -30,7 +30,7 @@ jobs: token: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }} fetch-depth: 0 - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache-workspaces: backend toolchain: 1.97.0 @@ -73,13 +73,13 @@ jobs: Rename-Item -Path ".\backend\target\release\windmill.exe" -NewName "windmill-ee.exe" - name: Upload binary artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v4.6.2 with: name: windmill-ee-binary path: ./backend/target/release/windmill-ee.exe - name: Upload dynamic libraries artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v4.6.2 with: name: windmill_duckdb_runner.exe path: ./backend/windmill-duckdb-ffi-internal/target/release/windmill_duckdb_runner.exe diff --git a/.github/workflows/change-versions.yml b/.github/workflows/change-versions.yml index eea62bf6b7..a18f9a9143 100644 --- a/.github/workflows/change-versions.yml +++ b/.github/workflows/change-versions.yml @@ -9,25 +9,25 @@ jobs: runs-on: ubicloud container: node:18 steps: - - uses: actions/create-github-app-token@v2 + - uses: actions/create-github-app-token@v2.2.2 id: app with: app-id: ${{ vars.INTERNAL_APP_ID }} private-key: ${{ secrets.INTERNAL_APP_KEY }} - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: token: ${{ steps.app.outputs.token }} - run: git config --system --add safe.directory /__w/windmill/windmill - name: Change versions run: ./.github/change-versions.sh "$(cat version.txt)" - - uses: actions-rs/toolchain@v1 + - uses: actions-rs/toolchain@v1.0.7 with: toolchain: stable - name: update lockfile run: | cd backend cargo generate-lockfile - - uses: stefanzweifel/git-auto-commit-action@v5 + - uses: stefanzweifel/git-auto-commit-action@v5.2.0 with: commit_user_name: windmill-internal-app[bot] commit_user_email: windmill-internal-app[bot]@users.noreply.github.com diff --git a/.github/workflows/check-docs-links.yml b/.github/workflows/check-docs-links.yml index e32e976f0c..f0d95139cd 100644 --- a/.github/workflows/check-docs-links.yml +++ b/.github/workflows/check-docs-links.yml @@ -11,12 +11,12 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: sparse-checkout: | frontend/src .github/scripts - - uses: actions/setup-node@v7 + - uses: actions/setup-node@v7.1.0 with: node-version: "22.x" - name: Verify docs links are not 404 diff --git a/.github/workflows/check-empty-fixture.yml b/.github/workflows/check-empty-fixture.yml index 4842260645..ceece46314 100644 --- a/.github/workflows/check-empty-fixture.yml +++ b/.github/workflows/check-empty-fixture.yml @@ -13,7 +13,7 @@ jobs: check-empty-fixture: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - name: Ensure fixtures/cli-sync/ has no committed snapshot run: bash fixtures/check-empty.sh diff --git a/.github/workflows/check-system-prompts.yml b/.github/workflows/check-system-prompts.yml index 370a177716..4c5b054ae3 100644 --- a/.github/workflows/check-system-prompts.yml +++ b/.github/workflows/check-system-prompts.yml @@ -26,9 +26,9 @@ jobs: check-freshness: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - - uses: actions/setup-python@v7 + - uses: actions/setup-python@v7.1.0 with: python-version: "3.12" diff --git a/.github/workflows/check-write-access.yml b/.github/workflows/check-write-access.yml index 097fc3b3dd..73a2190763 100644 --- a/.github/workflows/check-write-access.yml +++ b/.github/workflows/check-write-access.yml @@ -38,7 +38,7 @@ jobs: id: app if: vars.INTERNAL_APP_ID != '' continue-on-error: true - uses: actions/create-github-app-token@v2 + uses: actions/create-github-app-token@v2.2.2 with: app-id: ${{ vars.INTERNAL_APP_ID }} private-key: ${{ secrets.INTERNAL_APP_KEY }} diff --git a/.github/workflows/claude-plan.yml b/.github/workflows/claude-plan.yml index b3798c76f5..877b20acbb 100644 --- a/.github/workflows/claude-plan.yml +++ b/.github/workflows/claude-plan.yml @@ -38,12 +38,12 @@ jobs: id-token: write steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 with: fetch-depth: 1 - name: Run Claude Plan Action - uses: anthropics/claude-code-action@v1 + uses: anthropics/claude-code-action@v1.0.271 with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} allowed_bots: 'windmill-internal-app[bot]' diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 5250c5a04b..7069df858b 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -37,7 +37,7 @@ jobs: id-token: write steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 with: fetch-depth: 1 @@ -67,7 +67,7 @@ jobs: - name: Checkout EE repository if: steps.ee.outputs.available == 'true' - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -80,7 +80,7 @@ jobs: run: ./backend/substitute_ee_code.sh --copy --dir ./windmill-ee-private - name: Run Claude PR Action - uses: anthropics/claude-code-action@v1 + uses: anthropics/claude-code-action@v1.0.271 with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} allowed_bots: "windmill-internal-app[bot]" diff --git a/.github/workflows/cli-tests.yml b/.github/workflows/cli-tests.yml index 0db89d496b..f9934b54fd 100644 --- a/.github/workflows/cli-tests.yml +++ b/.github/workflows/cli-tests.yml @@ -40,10 +40,10 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v7 + uses: actions/setup-node@v7.1.0 with: node-version: "20" @@ -52,7 +52,7 @@ jobs: - name: Setup Bun id: setup-bun continue-on-error: true - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@v2.2.0 with: bun-version: latest @@ -63,7 +63,7 @@ jobs: - name: Setup Bun (retry) if: steps.setup-bun.outcome == 'failure' - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@v2.2.0 with: bun-version: latest @@ -95,23 +95,23 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 - name: Setup Rust toolchain - uses: actions-rust-lang/setup-rust-toolchain@v1 + uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache: true cache-workspaces: backend - name: Setup Node.js - uses: actions/setup-node@v7 + uses: actions/setup-node@v7.1.0 with: node-version: "20" - name: Setup Bun id: setup-bun continue-on-error: true - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@v2.2.0 with: bun-version: latest @@ -122,7 +122,7 @@ jobs: - name: Setup Bun (retry) if: steps.setup-bun.outcome == 'failure' - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@v2.2.0 with: bun-version: latest @@ -154,7 +154,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 - name: Setup PostgreSQL uses: ikalnytskyi/action-setup-postgres@v6 @@ -165,20 +165,20 @@ jobs: port: 5432 - name: Setup Rust toolchain - uses: actions-rust-lang/setup-rust-toolchain@v1 + uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache: true cache-workspaces: backend - name: Setup Node.js - uses: actions/setup-node@v7 + uses: actions/setup-node@v7.1.0 with: node-version: "20" - name: Setup Bun id: setup-bun continue-on-error: true - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@v2.2.0 with: bun-version: latest @@ -189,7 +189,7 @@ jobs: - name: Setup Bun (retry) if: steps.setup-bun.outcome == 'failure' - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@v2.2.0 with: bun-version: latest diff --git a/.github/workflows/codex-pr-review.yml b/.github/workflows/codex-pr-review.yml index e1628729d8..f36fd7c6e2 100644 --- a/.github/workflows/codex-pr-review.yml +++ b/.github/workflows/codex-pr-review.yml @@ -176,7 +176,7 @@ jobs: - name: Checkout repository if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true' - uses: actions/checkout@v5 + uses: actions/checkout@v5.1.0 with: ref: refs/pull/${{ steps.pr.outputs.pr_number }}/merge fetch-depth: 1 @@ -204,7 +204,7 @@ jobs: - name: Checkout EE repository if: steps.ee.outputs.available == 'true' - uses: actions/checkout@v5 + uses: actions/checkout@v5.1.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -218,7 +218,7 @@ jobs: - name: Set up Node.js if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true' - uses: actions/setup-node@v7 + uses: actions/setup-node@v7.1.0 with: node-version: 22 @@ -369,7 +369,7 @@ jobs: - name: Post Codex review comment if: steps.codex_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true' - uses: actions/github-script@v7 + uses: actions/github-script@v7.1.0 env: PR_NUMBER: ${{ steps.pr.outputs.pr_number }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} diff --git a/.github/workflows/docker-image-rpi4.yml b/.github/workflows/docker-image-rpi4.yml index fa5f4ba3fe..6db9baa2b6 100644 --- a/.github/workflows/docker-image-rpi4.yml +++ b/.github/workflows/docker-image-rpi4.yml @@ -16,7 +16,7 @@ jobs: build: runs-on: ubicloud steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: fetch-depth: 0 @@ -24,7 +24,7 @@ jobs: run: | echo "ee_repo_ref=$(cat ./backend/ee-repo-ref.txt)" >> "$GITHUB_ENV" - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -34,10 +34,10 @@ jobs: # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -49,7 +49,7 @@ jobs: - name: Docker meta id: meta-public - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} @@ -61,7 +61,7 @@ jobs: type=semver,pattern={{major}}.{{minor}} - name: Build and push publicly - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: . platforms: linux/amd64,linux/arm64 diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index a5823ef19c..c906369368 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -46,29 +46,31 @@ jobs: outputs: digest: ${{ steps.docker_build.outputs.digest }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: ref: ${{ github.ref }} + # GIT_VERSION is `git describe --tags`, which needs the history and + # tags but no file contents beyond the checked-out tree fetch-depth: 0 + filter: blob:none - name: Read EE repo commit hash run: | echo "ee_repo_ref=$(cat ./backend/ee-repo-ref.txt)" >> "$GITHUB_ENV" - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private ref: ${{ env.ee_repo_ref }} token: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }} - fetch-depth: 0 # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -80,7 +82,7 @@ jobs: - name: Docker meta id: meta-public - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} @@ -92,7 +94,7 @@ jobs: - name: Build and push publicly id: docker_build - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: . platforms: linux/amd64,linux/arm64 @@ -109,7 +111,7 @@ jobs: - name: Sign and attest release image if: startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' - uses: ./.github/actions/sign-attest-image + uses: $/.github/actions/sign-attest-image with: image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} digest: ${{ steps.docker_build.outputs.digest }} @@ -118,43 +120,48 @@ jobs: runs-on: ubicloud if: (github.event_name != 'workflow_dispatch') || github.event.inputs.ee outputs: - digest: ${{ steps.docker_build.outputs.digest }} + digest: ${{ steps.digest.outputs.digest }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: ref: ${{ github.ref }} + # GIT_VERSION is `git describe --tags`, which needs the history and + # tags but no file contents beyond the checked-out tree fetch-depth: 0 + filter: blob:none - name: Read EE repo commit hash run: | echo "ee_repo_ref=$(cat ./backend/ee-repo-ref.txt)" >> "$GITHUB_ENV" - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private ref: ${{ env.ee_repo_ref }} token: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }} - fetch-depth: 0 # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Docker meta id: meta-ee-public - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee flavor: | latest=false tags: | + type=raw,value=${{ env.DEV_SHA }} type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} + labels: | + org.opencontainers.image.licenses=Windmill-Enterprise-License - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -166,28 +173,54 @@ jobs: - name: Build and push publicly ee id: docker_build - uses: depot/build-push-action@v1 + uses: depot/bake-action@v1.13.0 + env: + WM_BUILD_VERSION: ${{ github.sha }} + SBOM: ${{ startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' }} with: - context: . - platforms: linux/amd64,linux/arm64 - push: true - sbom: ${{ startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' }} - build-args: | - features=ee - WM_BUILD_VERSION=${{ github.sha }} - tags: | - ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee:${{ env.DEV_SHA }} - ${{ steps.meta-ee-public.outputs.tags }} - labels: | - ${{ steps.meta-ee-public.outputs.labels }} - org.opencontainers.image.licenses=Windmill-Enterprise-License + files: | + ./.github/docker-bake-ee.hcl + ${{ steps.meta-ee-public.outputs.bake-file-tags }} + ${{ steps.meta-ee-public.outputs.bake-file-labels }} + targets: ${{ (startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch') && 'image,debuginfo' || 'image' }} + + - name: Read image digest + id: digest + env: + METADATA: ${{ steps.docker_build.outputs.metadata }} + run: | + digest=$(jq -er '.image["containerimage.digest"]' <<<"$METADATA") + echo "digest=$digest" | tee -a "$GITHUB_OUTPUT" - name: Sign and attest release image if: startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' - uses: ./.github/actions/sign-attest-image + uses: $/.github/actions/sign-attest-image with: image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee - digest: ${{ steps.docker_build.outputs.digest }} + digest: ${{ steps.digest.outputs.digest }} + + # 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. A failed upload must + # not fail build_ee: every EE image and the release binary wait on it. + - name: Upload debug files to private bucket + if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch' + continue-on-error: true + 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 }} + run: | + set -euo pipefail + trap 'echo "::error::EE debug files were not uploaded for $TAG"' ERR + ls -l ./debuginfo/linux_amd64/windmill.debug ./debuginfo/linux_arm64/windmill.debug + [[ "$GITHUB_REF" == refs/tags/v* ]] || exit 0 + aws configure set default.s3.multipart_chunksize 64MB + for arch in amd64 arm64; do + aws s3 cp "./debuginfo/linux_$arch/windmill.debug" \ + "s3://windmill-ee-debuginfo/$TAG/windmill-ee-$arch.debug" \ + --storage-class GLACIER_IR --only-show-errors + done attach_amd64_binary_to_release: needs: [build, build_ee] @@ -196,7 +229,7 @@ jobs: env: ARCH: amd64 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 # The runner disk cannot hold the CE and EE images at once, so each image # is pulled, extracted from and removed before the next one is pulled. @@ -229,71 +262,10 @@ jobs: ls -la release - name: Attach binary to release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v2.6.2 with: files: release/* - upload_ee_debug_to_s3: - needs: [build_ee] - runs-on: ubicloud - if: ${{ startsWith(github.ref, 'refs/tags/v') }} - strategy: - matrix: - platform: [linux/amd64, linux/arm64] - include: - - platform: linux/amd64 - arch: amd64 - - platform: linux/arm64 - arch: arm64 - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ github.ref }} - - - name: Read EE repo commit hash - run: | - echo "ee_repo_ref=$(cat ./backend/ee-repo-ref.txt)" >> "$GITHUB_ENV" - - - uses: actions/checkout@v4 - with: - repository: windmill-labs/windmill-ee-private - path: ./windmill-ee-private - ref: ${{ env.ee_repo_ref }} - token: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }} - - - name: Substitute EE code - run: | - ./backend/substitute_ee_code.sh --copy --dir ./windmill-ee-private - - - uses: depot/setup-action@v1 - - - name: Extract EE debug info from builder stage (depot cache hit) - uses: depot/build-push-action@v1 - with: - context: . - platforms: ${{ matrix.platform }} - target: debuginfo - build-args: | - features=ee - WM_BUILD_VERSION=${{ github.sha }} - outputs: type=local,dest=./debuginfo - - # 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: | - 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] # runs-on: ubicoud @@ -342,7 +314,7 @@ jobs: runs-on: ubicloud needs: [build_ee] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: ref: ${{ github.ref }} fetch-depth: 0 @@ -356,7 +328,7 @@ jobs: LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} run: cd integration_tests && ./run.sh - name: Archive logs - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v4.6.2 if: always() with: name: Windmill Integration Tests Logs @@ -370,11 +342,9 @@ jobs: github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) && (github.event_name != 'workflow_dispatch') steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 + - uses: actions/checkout@v4.4.0 - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -406,11 +376,9 @@ jobs: github.event_name != 'pull_request' && (github.event_name != 'workflow_dispatch') && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 + - uses: actions/checkout@v4.4.0 - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -461,10 +429,10 @@ jobs: # 0.69.3, pinned by digest so a republished tag cannot change what runs with release credentials. TRIVY_IMAGE: aquasec/trivy@sha256:bcc376de8d77cfe086a917230e818dc9f8528e3c852f7b1aff648949b6258d1c steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -481,7 +449,7 @@ jobs: trivy() { docker run --rm -v "$RUNNER_TEMP/trivy-cache:/root/.cache/trivy" -v "$PWD/scan:/out" "$TRIVY_IMAGE" "$@"; } trivy image -q --platform linux/amd64 \ --scanners vuln --format json -o /out/full.json "$IMAGE_REF" - .github/scripts/kernel-headers-vex.sh \ + .github/scripts/image-vex.sh \ "https://github.com/windmill-labs/windmill/releases/tag/${GITHUB_REF_NAME}#${{ matrix.image }}" \ scan/full.json > "scan/${{ matrix.image }}.openvex.json" trivy image -q --platform linux/amd64 \ @@ -491,7 +459,7 @@ jobs: --severity CRITICAL,HIGH -o "/out/${{ matrix.image }}.cves.txt" "/out/${{ matrix.image }}.trivy.json" - name: Attach scan results to the release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v2.6.2 with: files: | scan/${{ matrix.image }}.openvex.json @@ -521,7 +489,7 @@ jobs: done - name: Docker Scout report - uses: docker/scout-action@v1 + uses: docker/scout-action@v1.28.0 with: command: cves only-severities: critical,high @@ -534,7 +502,7 @@ jobs: # Filed under main: the Security tab only reads the default branch, so tag-only uploads # never close their alerts. `sha` is the release commit, which is on main. - name: Upload SARIF result - uses: github/codeql-action/upload-sarif@v4 + uses: github/codeql-action/upload-sarif@v4.39.3 with: sarif_file: scout.sarif.json category: docker-scout-${{ matrix.image }} @@ -570,39 +538,33 @@ jobs: # only-fixed: true publish_ecr_s3: - needs: [build_ee_full] + needs: [build_ee] runs-on: ubicloud-standard-2-arm if: ${{ startsWith(github.ref, 'refs/tags/v') }} env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 + - uses: actions/checkout@v4.4.0 - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 + uses: docker/setup-buildx-action@v2.10.0 - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - name: Get version from tag - id: version - run: echo "VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT" - - - uses: shrink/actions-docker-extract@v3 + - uses: shrink/actions-docker-extract@v3.1.0 id: extract with: image: |- - ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee-full:${{ steps.version.outputs.VERSION }} + ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee@${{ needs.build_ee.outputs.digest }} path: "/static_frontend/." - - uses: reggionick/s3-deploy@v4 + - uses: reggionick/s3-deploy@v4.0.0 with: folder: ${{ steps.extract.outputs.destination }} bucket: windmill-frontend @@ -613,19 +575,18 @@ jobs: needs: [build_ee] runs-on: ubicloud steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: - fetch-depth: 0 ref: ${{ github.ref }} # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Docker meta id: meta-ee-public - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee-cuda @@ -634,7 +595,7 @@ jobs: type=semver,pattern={{major}}.{{minor}} - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -642,7 +603,7 @@ jobs: - name: Build and push publicly ee id: docker_build - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: . platforms: linux/amd64 @@ -659,7 +620,7 @@ jobs: - name: Sign and attest release image if: startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' - uses: ./.github/actions/sign-attest-image + uses: $/.github/actions/sign-attest-image with: image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee-cuda digest: ${{ steps.docker_build.outputs.digest }} @@ -671,18 +632,16 @@ jobs: outputs: digest: ${{ steps.docker_build.outputs.digest }} steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 + - uses: actions/checkout@v4.4.0 # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Docker meta id: meta-ee-public - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-slim @@ -691,7 +650,7 @@ jobs: type=semver,pattern={{major}}.{{minor}} - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -699,7 +658,7 @@ jobs: - name: Build and push publicly ee id: docker_build - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: . platforms: linux/amd64 @@ -715,7 +674,7 @@ jobs: - name: Sign and attest release image if: startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' - uses: ./.github/actions/sign-attest-image + uses: $/.github/actions/sign-attest-image with: image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-slim digest: ${{ steps.docker_build.outputs.digest }} @@ -728,18 +687,16 @@ jobs: digest: ${{ steps.docker_build.outputs.digest }} steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 + - uses: actions/checkout@v4.4.0 # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Docker meta id: meta-ee-public - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee-slim @@ -749,7 +706,7 @@ jobs: type=semver,pattern={{major}}.{{minor}} - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -757,7 +714,7 @@ jobs: - name: Build and push publicly ee id: docker_build - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: . platforms: linux/amd64,linux/arm64 @@ -774,7 +731,7 @@ jobs: - name: Sign and attest release image if: startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' - uses: ./.github/actions/sign-attest-image + uses: $/.github/actions/sign-attest-image with: image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee-slim digest: ${{ steps.docker_build.outputs.digest }} @@ -784,18 +741,16 @@ jobs: needs: [build] runs-on: ubicloud steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 + - uses: actions/checkout@v4.4.0 # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Docker meta id: meta-public - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-full @@ -804,7 +759,7 @@ jobs: type=semver,pattern={{major}}.{{minor}} - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -812,7 +767,7 @@ jobs: - name: Build and push publicly id: docker_build - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: . platforms: linux/amd64,linux/arm64 @@ -828,7 +783,7 @@ jobs: - name: Sign and attest release image if: startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' - uses: ./.github/actions/sign-attest-image + uses: $/.github/actions/sign-attest-image with: image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-full digest: ${{ steps.docker_build.outputs.digest }} @@ -838,18 +793,16 @@ jobs: needs: [build_ee] runs-on: ubicloud steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 + - uses: actions/checkout@v4.4.0 # - name: Set up Docker Buildx # uses: docker/setup-buildx-action@v2 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Docker meta id: meta-ee-public - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee-full @@ -858,7 +811,7 @@ jobs: type=semver,pattern={{major}}.{{minor}} - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -866,7 +819,7 @@ jobs: - name: Build and push publicly ee id: docker_build - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: . platforms: linux/amd64,linux/arm64 @@ -883,7 +836,7 @@ jobs: - name: Sign and attest release image if: startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' - uses: ./.github/actions/sign-attest-image + uses: $/.github/actions/sign-attest-image with: image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}-ee-full digest: ${{ steps.docker_build.outputs.digest }} diff --git a/.github/workflows/frontend-check.yml b/.github/workflows/frontend-check.yml index 6347614e16..0a70c8dd05 100644 --- a/.github/workflows/frontend-check.yml +++ b/.github/workflows/frontend-check.yml @@ -17,8 +17,8 @@ jobs: npm_check: runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v7 + - uses: actions/checkout@v4.4.0 + - uses: actions/setup-node@v7.1.0 with: node-version: 24 cache: "npm" @@ -28,5 +28,5 @@ jobs: env: # svelte-check peaks past node's ~4GB default ceiling on this runner and aborts. NODE_OPTIONS: --max-old-space-size=8192 - run: cd frontend && npm ci && npm run generate-backend-client && npm run - check + run: cd frontend && npm ci && npm run lint && npm run generate-backend-client && + npm run check diff --git a/.github/workflows/gallery_on_release.yml b/.github/workflows/gallery_on_release.yml index c95903ccad..23e1034217 100644 --- a/.github/workflows/gallery_on_release.yml +++ b/.github/workflows/gallery_on_release.yml @@ -9,7 +9,7 @@ jobs: publish_gallery: runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - run: . ./powershell-client/publish.ps1 shell: pwsh env: diff --git a/.github/workflows/git-commands.yaml b/.github/workflows/git-commands.yaml index bf9009c800..af5330809f 100644 --- a/.github/workflows/git-commands.yaml +++ b/.github/workflows/git-commands.yaml @@ -43,14 +43,14 @@ jobs: --health-retries 5 steps: - - uses: actions/create-github-app-token@v2 + - uses: actions/create-github-app-token@v2.2.2 id: app with: app-id: ${{ vars.INTERNAL_APP_ID }} private-key: ${{ secrets.INTERNAL_APP_KEY }} - name: Comment on PR - Starting - uses: actions/github-script@v6 + uses: actions/github-script@v6.4.1 with: github-token: ${{ steps.app.outputs.token }} script: | @@ -63,21 +63,21 @@ jobs: }) - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v3.7.0 with: token: ${{ steps.app.outputs.token }} ref: ${{ github.event.issue.pull_request.head.ref }} fetch-depth: 0 - name: Checkout windmill-ee-private - uses: actions/checkout@v3 + uses: actions/checkout@v3.7.0 with: repository: windmill-labs/windmill-ee-private path: windmill-ee-private token: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }} # Setup Rust toolchain - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache-workspaces: backend toolchain: 1.97.0 @@ -136,7 +136,7 @@ jobs: git push origin ${{ env.BRANCH_NAME }} - name: Comment on PR - Completed - uses: actions/github-script@v6 + uses: actions/github-script@v6.4.1 with: github-token: ${{ steps.app.outputs.token }} script: | @@ -161,7 +161,7 @@ jobs: id-token: write steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 with: fetch-depth: 0 @@ -242,14 +242,14 @@ jobs: pull-requests: write issues: write steps: - - uses: actions/create-github-app-token@v2 + - uses: actions/create-github-app-token@v2.2.2 id: app with: app-id: ${{ vars.INTERNAL_APP_ID }} private-key: ${{ secrets.INTERNAL_APP_KEY }} - name: Comment on PR - Starting - uses: actions/github-script@v6 + uses: actions/github-script@v6.4.1 with: github-token: ${{ steps.app.outputs.token }} script: | @@ -262,14 +262,14 @@ jobs: }) - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v3.7.0 with: token: ${{ steps.app.outputs.token }} ref: ${{ github.event.issue.pull_request.head.ref }} fetch-depth: 0 - name: Checkout windmill-ee-private - uses: actions/checkout@v3 + uses: actions/checkout@v3.7.0 with: repository: windmill-labs/windmill-ee-private path: windmill-ee-private @@ -308,7 +308,7 @@ jobs: git push origin $BRANCH_NAME - name: Comment on PR - Completed - uses: actions/github-script@v6 + uses: actions/github-script@v6.4.1 with: github-token: ${{ steps.app.outputs.token }} script: | @@ -331,7 +331,7 @@ jobs: pull-requests: read issues: read steps: - - uses: actions/create-github-app-token@v2 + - uses: actions/create-github-app-token@v2.2.2 id: app with: app-id: ${{ vars.INTERNAL_APP_ID }} diff --git a/.github/workflows/git-sync-test.yml b/.github/workflows/git-sync-test.yml index 7d26392dee..7140bf257a 100644 --- a/.github/workflows/git-sync-test.yml +++ b/.github/workflows/git-sync-test.yml @@ -41,7 +41,7 @@ jobs: outputs: should_run: ${{ steps.check.outputs.should_run }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: fetch-depth: 0 @@ -107,7 +107,7 @@ jobs: --health-retries 5 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: ref: ${{ github.ref }} fetch-depth: 0 @@ -116,7 +116,7 @@ jobs: run: | echo "ee_repo_ref=$(cat ./backend/ee-repo-ref.txt)" >> "$GITHUB_ENV" - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -128,20 +128,20 @@ jobs: run: | cd backend && ./substitute_ee_code.sh --copy --dir ./windmill-ee-private - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache-workspaces: backend toolchain: 1.97.0 - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@v2.2.0 with: - bun-version: 1.4.4 + bun-version: 1.4.5 - - uses: denoland/setup-deno@v2 + - uses: denoland/setup-deno@v2.0.5 with: deno-version: v2.x - - uses: actions/setup-node@v7 + - uses: actions/setup-node@v7.1.0 with: node-version: "20" @@ -216,7 +216,7 @@ jobs: cd integration_tests && ../.venv/bin/python -m unittest -v test.git_sync_test - name: Archive logs - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v4.6.2 if: always() with: name: Git Sync Integration Tests Logs diff --git a/.github/workflows/go_on_release.yml b/.github/workflows/go_on_release.yml index 6e53db09e7..1bfad90b4a 100644 --- a/.github/workflows/go_on_release.yml +++ b/.github/workflows/go_on_release.yml @@ -12,8 +12,8 @@ jobs: build_go_and_push_to_repo: runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 - - uses: actions/setup-go@v7 + - uses: actions/checkout@v4.4.0 + - uses: actions/setup-go@v7.0.0 - name: install_jq run: | sudo apt-get update @@ -27,7 +27,7 @@ jobs: go build - name: Pushes to another repository id: push_directory - uses: cpina/github-action-push-to-another-repository@55306faa4ed53b815ae49e564af8cfb359d32ae2 # v1.7.3 + uses: cpina/github-action-push-to-another-repository@v1.7.3 env: API_TOKEN_GITHUB: ${{ secrets.DENO_PAT }} with: @@ -42,7 +42,7 @@ jobs: needs: [build_go_and_push_to_repo] runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: repository: ${{ github.repository_owner }}/${{ env.repo }} token: ${{ secrets.DENO_PAT }} diff --git a/.github/workflows/helmchart_on_release.yml b/.github/workflows/helmchart_on_release.yml index 0a4ee872ce..27d787c000 100644 --- a/.github/workflows/helmchart_on_release.yml +++ b/.github/workflows/helmchart_on_release.yml @@ -11,14 +11,14 @@ jobs: steps: - name: Generate an installation token id: app - uses: actions/create-github-app-token@v2 + uses: actions/create-github-app-token@v2.2.2 with: app-id: ${{ vars.INTERNAL_APP_ID }} private-key: ${{ secrets.INTERNAL_APP_KEY }} owner: windmill-labs - name: Checkout on helm repository - uses: actions/checkout@v3 + uses: actions/checkout@v3.7.0 with: repository: windmill-labs/windmill-helm-charts token: ${{ steps.app.outputs.token }} diff --git a/.github/workflows/jsr_on_release.yml b/.github/workflows/jsr_on_release.yml index 4a9d443589..37235c168e 100644 --- a/.github/workflows/jsr_on_release.yml +++ b/.github/workflows/jsr_on_release.yml @@ -12,5 +12,5 @@ jobs: contents: read id-token: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - run: cd typescript-client && ./publish.jsr.sh diff --git a/.github/workflows/linear-claude.yaml b/.github/workflows/linear-claude.yaml index c74cfeba1d..097b4ca361 100644 --- a/.github/workflows/linear-claude.yaml +++ b/.github/workflows/linear-claude.yaml @@ -14,7 +14,7 @@ jobs: id-token: write steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 with: fetch-depth: 1 diff --git a/.github/workflows/npm_on_release.yml b/.github/workflows/npm_on_release.yml index a2bd974daa..33318a1282 100644 --- a/.github/workflows/npm_on_release.yml +++ b/.github/workflows/npm_on_release.yml @@ -9,8 +9,8 @@ jobs: publish_typescript_client: runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v7 + - uses: actions/checkout@v4.4.0 + - uses: actions/setup-node@v7.1.0 with: node-version: "20.x" registry-url: "https://registry.npmjs.org" @@ -25,8 +25,8 @@ jobs: contents: read id-token: write steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v7 + - uses: actions/checkout@v4.4.0 + - uses: actions/setup-node@v7.1.0 with: node-version: "24.x" registry-url: "https://registry.npmjs.org" @@ -34,12 +34,12 @@ jobs: publish_cli: runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v7 + - uses: actions/checkout@v4.4.0 + - uses: actions/setup-node@v7.1.0 with: node-version: "20.x" registry-url: "https://registry.npmjs.org" - - uses: oven-sh/setup-bun@v2 + - uses: oven-sh/setup-bun@v2.2.0 with: bun-version: latest - run: cd cli && ./build.sh && cd npm && npm publish --access public diff --git a/.github/workflows/pi-pr-review.yml b/.github/workflows/pi-pr-review.yml index 4b57db7b78..49f9876525 100644 --- a/.github/workflows/pi-pr-review.yml +++ b/.github/workflows/pi-pr-review.yml @@ -169,7 +169,7 @@ jobs: - name: Checkout repository if: steps.pi_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true' - uses: actions/checkout@v5 + uses: actions/checkout@v5.1.0 with: ref: refs/pull/${{ steps.pr.outputs.pr_number }}/merge fetch-depth: 1 @@ -197,7 +197,7 @@ jobs: - name: Checkout EE repository if: steps.ee.outputs.available == 'true' - uses: actions/checkout@v5 + uses: actions/checkout@v5.1.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -211,7 +211,7 @@ jobs: - name: Set up Node.js if: steps.pi_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true' - uses: actions/setup-node@v7 + uses: actions/setup-node@v7.1.0 with: node-version: 22 @@ -421,7 +421,7 @@ jobs: - name: Post Pi review comment if: steps.pi_config.outputs.enabled == 'true' && steps.pr.outputs.skip != 'true' - uses: actions/github-script@v7 + uses: actions/github-script@v7.1.0 env: PR_NUMBER: ${{ steps.pr.outputs.pr_number }} DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }} diff --git a/.github/workflows/pr-ready-review.yml b/.github/workflows/pr-ready-review.yml index 4b88273cad..012fb820bb 100644 --- a/.github/workflows/pr-ready-review.yml +++ b/.github/workflows/pr-ready-review.yml @@ -96,7 +96,7 @@ jobs: - name: Checkout repository if: steps.marker.outputs.skip != 'true' - uses: actions/checkout@v5 + uses: actions/checkout@v5.1.0 with: fetch-depth: 1 @@ -115,7 +115,7 @@ jobs: - name: Checkout EE repository if: steps.ee.outputs.available == 'true' - uses: actions/checkout@v5 + uses: actions/checkout@v5.1.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -198,7 +198,7 @@ jobs: - name: Automatic PR Review if: steps.marker.outputs.skip != 'true' - uses: anthropics/claude-code-action@v1 + uses: anthropics/claude-code-action@v1.0.271 with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} track_progress: true diff --git a/.github/workflows/publish-cli-docs.yml b/.github/workflows/publish-cli-docs.yml index d6a2bdb332..2f9e38602a 100644 --- a/.github/workflows/publish-cli-docs.yml +++ b/.github/workflows/publish-cli-docs.yml @@ -26,19 +26,19 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout windmill (source of truth) - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 with: path: windmill - name: Checkout windmill-cli-docs (publish target) - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-cli-docs path: windmill-cli-docs ssh-key: ${{ secrets.CLI_DOCS_DEPLOY_KEY }} fetch-depth: 0 - - uses: actions/setup-python@v7 + - uses: actions/setup-python@v7.1.0 with: python-version: "3.12" diff --git a/.github/workflows/publish-mcp-registry.yml b/.github/workflows/publish-mcp-registry.yml new file mode 100644 index 0000000000..3f865549e5 --- /dev/null +++ b/.github/workflows/publish-mcp-registry.yml @@ -0,0 +1,133 @@ +name: Publish to MCP Registry + +# Publishes .github/mcp-registry/server.json (name io.github.windmill-labs/windmill) +# to the official MCP Registry (registry.modelcontextprotocol.io). GitHub OIDC from +# a repository owned by windmill-labs grants the io.github.windmill-labs/* namespace, +# so no PAT or secret is needed. +# +# Manual only. With publish=false (the default) it only stamps the version and +# validates. With publish=true it also logs in and publishes, and only from main. +# Each version can be published once; use the current Windmill release version. + +on: + workflow_dispatch: + inputs: + version: + description: "Version to publish, e.g. 1.868.0 (current Windmill release). Each version can be published once." + required: true + type: string + publish: + description: "Publish to the registry (false = validate only)" + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: publish-mcp-registry + cancel-in-progress: false + +env: + # Bump deliberately; the binary is verified against the release workflow's Sigstore identity. + MCP_PUBLISHER_VERSION: v1.8.9 + SERVER_JSON: .github/mcp-registry/server.json + +jobs: + validate: + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@v4.4.0 + with: + persist-credentials: false + + - name: Set version + env: + VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + version="${VERSION#v}" + if ! [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "::error::version must look like 1.868.0" + exit 1 + fi + jq --arg v "$version" '.version = $v' "$SERVER_JSON" > "$RUNNER_TEMP/server.json" + mv "$RUNNER_TEMP/server.json" "$SERVER_JSON" + jq -r '.name + " " + .version' "$SERVER_JSON" + + - name: Install cosign + uses: sigstore/cosign-installer@v4.1.2 + + - name: Download and verify mcp-publisher + run: | + set -euo pipefail + archive="mcp-publisher_linux_amd64.tar.gz" + base_url="https://github.com/modelcontextprotocol/registry/releases/download/${MCP_PUBLISHER_VERSION}" + curl --fail --location --silent --show-error --output "$archive" "$base_url/$archive" + curl --fail --location --silent --show-error --output "$archive.sigstore.json" "$base_url/$archive.sigstore.json" + cosign verify-blob \ + --bundle "$archive.sigstore.json" \ + --certificate-identity "https://github.com/modelcontextprotocol/registry/.github/workflows/release.yml@refs/tags/${MCP_PUBLISHER_VERSION}" \ + --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \ + "$archive" + tar xzf "$archive" mcp-publisher + rm -f "$archive" "$archive.sigstore.json" + + - name: Validate server.json + run: ./mcp-publisher validate "$SERVER_JSON" + + - name: Refuse to publish from a branch other than main + if: ${{ inputs.publish && github.ref != 'refs/heads/main' }} + run: | + echo "::error::publish=true is only allowed when dispatched on main" + exit 1 + + publish: + needs: validate + if: ${{ inputs.publish && github.ref == 'refs/heads/main' }} + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + id-token: write # GitHub OIDC login to the MCP Registry + steps: + - uses: actions/checkout@v4.4.0 + with: + persist-credentials: false + + - name: Set version + env: + VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + version="${VERSION#v}" + jq --arg v "$version" '.version = $v' "$SERVER_JSON" > "$RUNNER_TEMP/server.json" + mv "$RUNNER_TEMP/server.json" "$SERVER_JSON" + jq -r '.name + " " + .version' "$SERVER_JSON" + + - name: Install cosign + uses: sigstore/cosign-installer@v4.1.2 + + - name: Download and verify mcp-publisher + run: | + set -euo pipefail + archive="mcp-publisher_linux_amd64.tar.gz" + base_url="https://github.com/modelcontextprotocol/registry/releases/download/${MCP_PUBLISHER_VERSION}" + curl --fail --location --silent --show-error --output "$archive" "$base_url/$archive" + curl --fail --location --silent --show-error --output "$archive.sigstore.json" "$base_url/$archive.sigstore.json" + cosign verify-blob \ + --bundle "$archive.sigstore.json" \ + --certificate-identity "https://github.com/modelcontextprotocol/registry/.github/workflows/release.yml@refs/tags/${MCP_PUBLISHER_VERSION}" \ + --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \ + "$archive" + tar xzf "$archive" mcp-publisher + rm -f "$archive" "$archive.sigstore.json" + + - name: Log in with GitHub OIDC + run: ./mcp-publisher login github-oidc + + - name: Publish + run: ./mcp-publisher publish "$SERVER_JSON" diff --git a/.github/workflows/publish_extra.yml b/.github/workflows/publish_extra.yml index c1db4a654d..1ed97d1904 100644 --- a/.github/workflows/publish_extra.yml +++ b/.github/workflows/publish_extra.yml @@ -13,32 +13,66 @@ on: permissions: write-all jobs: - sleep: + # A release builds on its own ee-slim, pinned by digest (:latest is still the + # previous release while this one builds), and waits for its python client to + # be on PyPI, since lsp/Pipfile requires it. + base_image: runs-on: ubicloud + outputs: + image: ${{ steps.base.outputs.image }} steps: - - name: Sleep for 900 seconds waiting for pypi to update index - if: startsWith(github.ref, 'refs/tags/v') - run: sleep 900 + - name: Wait for this release's ee-slim image and PyPI client + id: base shell: bash + env: + IMAGE: ${{ env.REGISTRY }}/${{ github.repository }}-ee-slim + run: | + set -euo pipefail + if [[ "$GITHUB_REF" != refs/tags/v* ]]; then + echo "image=$IMAGE:latest" >> "$GITHUB_OUTPUT" + exit 0 + fi + version="${GITHUB_REF_NAME#v}" + deadline=$((SECONDS + 75 * 60)) + on_pypi() { + local page + page=$(curl -fsS -H 'Cache-Control: max-age=0' https://pypi.org/simple/wmill/) || return 1 + grep -qF -e "wmill-${version}-py" -e "wmill-${version}.tar.gz" <<<"$page" + } + until on_pypi; do + (( SECONDS < deadline )) || { echo "wmill $version is not on PyPI"; exit 1; } + sleep 20 + done + echo "wmill $version is on PyPI" + # A re-pushed tag finds the previous attempt's image under the same tag, + # so wait for the one built from this commit. + revision() { + docker buildx imagetools inspect "$IMAGE:$version" --format \ + '{{ index (index .Image "linux/amd64").Config.Labels "org.opencontainers.image.revision" }}' 2>/dev/null + } + until [[ "$(revision)" == "$GITHUB_SHA" ]]; do + (( SECONDS < deadline )) || { echo "$IMAGE:$version for $GITHUB_SHA was never pushed"; exit 1; } + sleep 30 + done + digest=$(docker buildx imagetools inspect "$IMAGE:$version" --format '{{.Manifest.Digest}}') + echo "image=$IMAGE@$digest" | tee -a "$GITHUB_OUTPUT" # Build and test the image before publishing test_extra: - needs: [sleep] + needs: [base_image] runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 + - uses: actions/checkout@v4.4.0 - name: Setup Bun - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@v2.2.0 with: bun-version: latest # Matches the Node major DockerfileExtra installs. The pin is load-bearing: # glob arguments to `node --test` need Node >= 21. - name: Setup Node - uses: actions/setup-node@v4 + uses: actions/setup-node@v4.4.0 with: node-version: 22 @@ -54,14 +88,16 @@ jobs: run: bash docker/test_entrypoint_extra.sh - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@v3.12.0 - name: Build test image - uses: docker/build-push-action@v7 + uses: docker/build-push-action@v7.4.0 with: context: . file: ./docker/DockerfileExtra load: true + build-args: | + BASE_IMAGE=${{ needs.base_image.outputs.image }} tags: windmill-extra:test cache-from: type=gha cache-to: type=gha,mode=max @@ -102,21 +138,19 @@ jobs: docker rm windmill-extra-test || true publish_extra: - needs: [sleep, test_extra] + needs: [base_image, test_extra] # a tag-targeted dispatch would republish the release tags unsigned, # un-verifying the release; to republish a release, re-push its tag if: github.event_name == 'push' || !startsWith(github.ref, 'refs/tags/') runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 + - uses: actions/checkout@v4.4.0 - - uses: depot/setup-action@v1 + - uses: depot/setup-action@v1.7.2 - name: Docker meta id: meta - uses: docker/metadata-action@v5 + uses: docker/metadata-action@v5.10.0 with: images: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} @@ -127,7 +161,7 @@ jobs: type=semver,pattern={{major}}.{{minor}} - name: Login to registry - uses: docker/login-action@v3 + uses: docker/login-action@v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -135,12 +169,14 @@ jobs: - name: Build and push publicly id: docker_build - uses: depot/build-push-action@v1 + uses: depot/build-push-action@v1.19.0 with: context: . file: ./docker/DockerfileExtra platforms: linux/amd64,linux/arm64 push: true + build-args: | + BASE_IMAGE=${{ needs.base_image.outputs.image }} sbom: ${{ startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' }} tags: | ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest @@ -151,7 +187,7 @@ jobs: - name: Sign and attest release image if: startsWith(github.ref, 'refs/tags/v') && github.event_name == 'push' - uses: ./.github/actions/sign-attest-image + uses: $/.github/actions/sign-attest-image with: image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} digest: ${{ steps.docker_build.outputs.digest }} diff --git a/.github/workflows/publish_windows_worker.yml b/.github/workflows/publish_windows_worker.yml index ecceff03ab..b27d12631b 100644 --- a/.github/workflows/publish_windows_worker.yml +++ b/.github/workflows/publish_windows_worker.yml @@ -15,7 +15,7 @@ jobs: cargo_build_windows: runs-on: blacksmith-16vcpu-windows-2025 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - name: Read EE repo commit hash shell: pwsh @@ -24,7 +24,7 @@ jobs: echo "ee_repo_ref=$ee_repo_ref" | Out-File -FilePath $env:GITHUB_ENV -Append - name: Checkout windmill-ee-private repository - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 with: repository: windmill-labs/windmill-ee-private path: ./windmill-ee-private @@ -32,7 +32,7 @@ jobs: token: ${{ secrets.WINDMILL_EE_PRIVATE_ACCESS }} fetch-depth: 0 - - uses: actions-rust-lang/setup-rust-toolchain@v1 + - uses: actions-rust-lang/setup-rust-toolchain@v1.17.0 with: cache-workspaces: backend toolchain: 1.97.0 @@ -67,13 +67,13 @@ jobs: Rename-Item -Path ".\backend\target\release\windmill.exe" -NewName "windmill-ee.exe" - name: Attach binary to release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v2.6.2 with: files: | ./backend/target/release/windmill-ee.exe - name: Attach the DuckDB runner to release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v2.6.2 with: files: | ./backend/windmill-duckdb-ffi-internal/target/release/windmill_duckdb_runner.exe diff --git a/.github/workflows/pypi_on_release.yml b/.github/workflows/pypi_on_release.yml index 39a3e11b2e..4bcaf6b8e5 100644 --- a/.github/workflows/pypi_on_release.yml +++ b/.github/workflows/pypi_on_release.yml @@ -7,12 +7,13 @@ on: jobs: publish_pypi: - runs-on: ubicloud-standard-8 + # openapi-python-client peaks near 32 GB on the dereferenced spec + runs-on: ubicloud-standard-16 if: startsWith(github.ref, 'refs/tags/v') container: image: ghcr.io/windmill-labs/python-client-builder steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - name: Upload python client env: PYPI_PASSWORD: ${{ secrets.PYPI_PASSWORD }} diff --git a/.github/workflows/refresh-docs-snapshot.yml b/.github/workflows/refresh-docs-snapshot.yml index a000f44df8..db365f5a50 100644 --- a/.github/workflows/refresh-docs-snapshot.yml +++ b/.github/workflows/refresh-docs-snapshot.yml @@ -17,12 +17,12 @@ jobs: contents: write pull-requests: write steps: - - uses: actions/create-github-app-token@v2 + - uses: actions/create-github-app-token@v2.2.2 id: app with: app-id: ${{ vars.INTERNAL_APP_ID }} private-key: ${{ secrets.INTERNAL_APP_KEY }} - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 with: token: ${{ steps.app.outputs.token }} - name: Fetch + re-gzip docs snapshot @@ -37,7 +37,7 @@ jobs: pages=$(gzip -dc llms-full.txt.gz | grep -c '^Source:' || true) echo "pages in snapshot: $pages" test "${pages:-0}" -ge 200 - - uses: peter-evans/create-pull-request@v6 + - uses: peter-evans/create-pull-request@v6.1.0 with: token: ${{ steps.app.outputs.token }} branch: chore/refresh-docs-snapshot diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 2f7dcde204..b9740650ad 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -12,6 +12,6 @@ jobs: # a `release-type` input instead re-derives the last released version by # paginating every GitHub release, which on a repo this size is slow enough # to fail intermittently. - - uses: googleapis/release-please-action@v5 + - uses: googleapis/release-please-action@v5.0.0 with: token: ${{ secrets.PAT_TOKEN }} diff --git a/.github/workflows/rust-client-check.yml b/.github/workflows/rust-client-check.yml index 32f06f5b85..0fd4d4e17a 100644 --- a/.github/workflows/rust-client-check.yml +++ b/.github/workflows/rust-client-check.yml @@ -17,8 +17,8 @@ jobs: check_rust_client: runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 - - uses: cachix/install-nix-action@v31 + - uses: actions/checkout@v4.4.0 + - uses: cachix/install-nix-action@v31.11.5 - name: Check rust client builds run: cd rust-client && nix develop ../ --command ./dev.nu --check timeout-minutes: 16 \ No newline at end of file diff --git a/.github/workflows/rust_on_release.yml b/.github/workflows/rust_on_release.yml index e23549e5e7..9d61bbc832 100644 --- a/.github/workflows/rust_on_release.yml +++ b/.github/workflows/rust_on_release.yml @@ -9,8 +9,8 @@ jobs: build_rust_and_publish_to_crates_io: runs-on: ubicloud-standard-8 steps: - - uses: actions/checkout@v4 - - uses: cachix/install-nix-action@v31 + - uses: actions/checkout@v4.4.0 + - uses: cachix/install-nix-action@v31.11.5 - run: cd rust-client && nix develop ../ --command ./dev.nu --check --publish env: CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }} diff --git a/.github/workflows/sdk-tests.yml b/.github/workflows/sdk-tests.yml index 260fbb3a02..2563d00f18 100644 --- a/.github/workflows/sdk-tests.yml +++ b/.github/workflows/sdk-tests.yml @@ -19,10 +19,10 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 - name: Setup Bun - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@v2.2.0 with: bun-version: latest @@ -36,14 +36,14 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 - name: Setup Bun - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@v2.2.0 with: bun-version: latest - - uses: actions/setup-node@v7 + - uses: actions/setup-node@v7.1.0 with: node-version: "20.x" @@ -55,10 +55,10 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 - name: Setup uv - uses: astral-sh/setup-uv@v7 + uses: astral-sh/setup-uv@v10.3.3 # The interpreter is named explicitly: on a clean checkout uv picks the # runner's system python and stops with "not compatible with the locked diff --git a/.github/workflows/sign-cla.yml b/.github/workflows/sign-cla.yml index 52329b6119..675392261a 100644 --- a/.github/workflows/sign-cla.yml +++ b/.github/workflows/sign-cla.yml @@ -15,7 +15,7 @@ jobs: == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target' # Beta Release - uses: cla-assistant/github-action@v2.6.1 + uses: contributor-assistant/github-action@v2.6.1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} PERSONAL_ACCESS_TOKEN: ${{ secrets.CLA_PAT }} diff --git a/.github/workflows/validate-openapi.yml b/.github/workflows/validate-openapi.yml index 846621b503..35f3d81756 100644 --- a/.github/workflows/validate-openapi.yml +++ b/.github/workflows/validate-openapi.yml @@ -12,10 +12,10 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 - name: Set up Node.js - uses: actions/setup-node@v7 + uses: actions/setup-node@v7.1.0 with: node-version: '20' diff --git a/.github/workflows/weekly-pr-summary.yml b/.github/workflows/weekly-pr-summary.yml index 14551e9943..64597e7c42 100644 --- a/.github/workflows/weekly-pr-summary.yml +++ b/.github/workflows/weekly-pr-summary.yml @@ -18,12 +18,12 @@ jobs: id-token: write steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v4.4.0 with: fetch-depth: 1 - name: Generate Weekly PR Summary - uses: anthropics/claude-code-action@v1 + uses: anthropics/claude-code-action@v1.0.271 with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} prompt: | diff --git a/.github/workflows/yaml-validator-tests.yml b/.github/workflows/yaml-validator-tests.yml index c5524312cb..b6dd156972 100644 --- a/.github/workflows/yaml-validator-tests.yml +++ b/.github/workflows/yaml-validator-tests.yml @@ -22,9 +22,9 @@ jobs: test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4.4.0 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@v7.1.0 with: node-version: "20" diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ebb4b7f4d0..0120e7188e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.866.0" + ".": "1.880.1" } diff --git a/AGENTS.md b/AGENTS.md index f22ec56fe6..2fa3c6440d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,6 +56,9 @@ Open-source platform for internal tools, workflows, API integrations, background - **Operator builder rights**: `docs/operator-builder-rights.md` — the workspace settings that let operators compose flows, AI agents 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 +- **AI agents**: `docs/reusable-ai-agents.md` — saved agents, linked from flow steps and also run + on their own (page, API, Slack, apps) as a one-step flow, so flow and chat-flow behaviour + reaches them too; memory, approvals and questions - **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 @@ -72,7 +75,7 @@ Open-source platform for internal tools, workflows, API integrations, background - **Domain vocabulary**: `CONTEXT.md` — the words this codebase uses for its own concepts (step, step setting, trigger step, …). Name things the way it does. - **CLI commands**: when adding/modifying/removing a command, subcommand, option, or description in `cli/src/commands/`, run `python system_prompts/generate.py` to refresh `system_prompts/auto-generated/` and `cli/src/guidance/skills.gen.ts`. The CLI docs the agents use to operate `wmill` are derived from the source — stale generated files give agents the wrong flags. - **AI guidance** (chat prompts and CLI skills): what the AI knows about Windmill itself — how flows, scripts, apps, pipelines and resources work — is written once, in `system_prompts/base/` and `system_prompts/languages/`, and `system_prompts/generate.py` builds both the chat's `$system_prompts` exports and the CLI's skills from it. Add or change such guidance there, never inline in one consumer: a sentence only one side should see goes in a `` / `` block, and a new file reaches both through the `TOPICS` table. The chat prompt builders under `frontend/src/lib/components/copilot/chat/` add only tool plumbing and runtime values, and shared markdown names no chat tool, since it reaches every chat mode. Rerun `generate.py` after editing; `system_prompts/README.md` has the details. -- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve and by the token forms' Build and run access, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `ai_session_tools/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). The instructions are one template (`EXTERNAL_PROMPT` in `chat/global/core.ts`, with `{{#flag}}` blocks rendered by `promptTemplate.ts`), and the generator exports the flags and variables of each access profile: the token's scope and, for a full token, the caller's role and whether the deploy rules let them deploy. The server only renders it, with the profile the key `prompt_profile` (`ai_session_tools/instructions.rs`) builds, which must match the generator's; its renderer must match `promptTemplate.ts`, which a hash per profile pins. In a workspace with `DisableDirectDeployment` every full token, an admin's included, is held to read-and-run there (`workspace_access` in `mcp/core.rs`), as the chat's session is (`protects` in `chat/global/sessionAccess.ts`); the two copies of that rule change together. What a tool *does* is written once, in a Rust handler the chat also calls (`POST /w/{workspace}/ai_session_tools/{name}`, through `chat/global/backendSessionTools.ts`); the browser applies the effects it returns, saving drafts through its own draft store. A new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `ai_session_tools/mod.rs` fails otherwise). Still written twice, so a behaviour change must be mirrored: `deploy_workspace_item` and `diff` (the chat uses the UI's shared deploy and diff code), and the run tools' form side (argument coercion, secrets, plan mode, the outcome text), where the chat resolves and starts the run on the server but owns the form in between; both sides test their argument handling against `ai_session_tools/run_args_cases.json`, so a change there comes with a case. For MCP Apps clients the server adds tools of its own, defined in Rust (`ai_session_tools/views.rs`) rather than generated, and not offered to the chat, which draws its own cards: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. +- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve and by the token forms' Build and run access, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `ai_session_tools/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). The instructions are one template (`EXTERNAL_PROMPT` in `chat/global/core.ts`, with `{{#flag}}` blocks rendered by `promptTemplate.ts`), and the generator exports the flags and variables of each access profile: the token's scope and, for a full token, the caller's role and whether the deploy rules let them deploy. The server only renders it, with the profile the key `prompt_profile` (`ai_session_tools/instructions.rs`) builds, which must match the generator's; its renderer must match `promptTemplate.ts`, which a hash per profile pins. In a workspace with `DisableDirectDeployment` every full token, an admin's included, is held to read-and-run there (`workspace_access` in `mcp/core.rs`), as the chat's session is (`protects` in `chat/global/sessionAccess.ts`), and a member whose role cannot run is held to read-only, with no run tools (`session_ctx_with`, and `capabilitiesForRole` in the chat); the two copies of each rule change together. What a tool *does* is written once, in a Rust handler the chat also calls (`POST /w/{workspace}/ai_session_tools/{name}`, through `chat/global/backendSessionTools.ts`); the browser applies the effects it returns, saving drafts through its own draft store. A new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `ai_session_tools/mod.rs` fails otherwise). Still written twice, so a behaviour change must be mirrored: `deploy_workspace_item` and `diff` (the chat uses the UI's shared deploy and diff code), and the run tools' form side (argument coercion, secrets, plan mode, the outcome text), where the chat resolves and starts the run on the server but owns the form in between; both sides test their argument handling against `ai_session_tools/run_args_cases.json`, so a change there comes with a case. For MCP Apps clients the server adds tools of its own, defined in Rust (`ai_session_tools/views.rs`) rather than generated, and not offered to the chat, which draws its own cards: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. - **Session recorder**: `frontend/src/lib/components/recording/` is also the recorder `wmill app dev --recording` serves, vendored into the CLI as `cli/src/commands/app/devRecorderBundle.gen.ts`. After changing `rawAppSnapshot.ts` or `rawAppRecording.svelte.ts`, run `bun run gen:dev-recorder` from `cli/` (`cli/test/dev_recorder_bundle_unit.test.ts` fails otherwise). - **Raw-app policy**: `frontend/src/lib/components/raw_apps/rawAppPolicy.ts` also derives the policy the server's raw-app deploy stores, vendored into the bundle job as `backend/windmill-api/src/apps_raw_policy.gen.js`. After changing it or anything it imports, run `bun run gen:app-policy` from `cli/` (`cli/test/app_policy_bundle_unit.test.ts` fails otherwise). It rides in the job rather than being read from the CLI the job runs because the images install `windmill-cli` unpinned, so an image can carry one older than its server. diff --git a/CHANGELOG.md b/CHANGELOG.md index e893e893fa..26a0b3af13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,334 @@ # Changelog +## [1.880.1](https://github.com/windmill-labs/windmill/compare/v1.880.0...v1.880.1) (2026-11-19) + + +### Bug Fixes + +* make the mssql database manager work under case-sensitive collations ([#12550](https://github.com/windmill-labs/windmill/issues/12550)) ([cb824de](https://github.com/windmill-labs/windmill/commit/cb824de928b35aee34bf1dda3a385d04eff277b3)) + +## [1.880.0](https://github.com/windmill-labs/windmill/compare/v1.879.0...v1.880.0) (2026-11-19) + + +### Features + +* record and download a worker group's autoscaling decisions ([#12542](https://github.com/windmill-labs/windmill/issues/12542)) ([5583c68](https://github.com/windmill-labs/windmill/commit/5583c680d4db7aa333227f09c2667733156cbe7a)) + + +### Bug Fixes + +* **api:** noindex public app pages on cloud ([#12547](https://github.com/windmill-labs/windmill/issues/12547)) ([cbf44b3](https://github.com/windmill-labs/windmill/commit/cbf44b36f339ae8fa624e70a34840cb82c5e32ca)) +* hold the configured AI key to its output token limits ([#12543](https://github.com/windmill-labs/windmill/issues/12543)) ([6c2c5cf](https://github.com/windmill-labs/windmill/commit/6c2c5cf46c8b5edb052e359d5dff76ef42b75ce2)) +* keep the AI sessions view mounted across navigation ([#12479](https://github.com/windmill-labs/windmill/issues/12479)) ([7fa093f](https://github.com/windmill-labs/windmill/commit/7fa093f7d493982add660e1ebeef96fb24c16411)) +* name a step inside a subflow sub:inner in flow tests ([#12549](https://github.com/windmill-labs/windmill/issues/12549)) ([50daf70](https://github.com/windmill-labs/windmill/commit/50daf70337dcec0749ea715942c1c0ec4f6e3b7e)) + +## [1.879.0](https://github.com/windmill-labs/windmill/compare/v1.878.0...v1.879.0) (2026-11-19) + + +### Features + +* **home:** link each primitive's explainer video in the New picker ([#12536](https://github.com/windmill-labs/windmill/issues/12536)) ([3591598](https://github.com/windmill-labs/windmill/commit/3591598d03f528b54aeb68349845c9958c0a73a9)) +* test flows from the SDKs with mocked or replaced steps, subflows included ([#12538](https://github.com/windmill-labs/windmill/issues/12538)) ([98439f8](https://github.com/windmill-labs/windmill/commit/98439f8521999222347f48b50bd032412e604439)) + + +### Bug Fixes + +* explain a fractional retry multiplier, check schedule retries on save ([#12539](https://github.com/windmill-labs/windmill/issues/12539)) ([558f83f](https://github.com/windmill-labs/windmill/commit/558f83fc9c74480369bab2ac88a8951136230651)) +* keep dedicated workers counted, busy and out of zombie restarts ([#12540](https://github.com/windmill-labs/windmill/issues/12540)) ([7b23884](https://github.com/windmill-labs/windmill/commit/7b2388476f0b72b5e403f5b3086cae5cb0a0e2e6)) +* keep the first undo after a redo in the flow editor ([#12537](https://github.com/windmill-labs/windmill/issues/12537)) ([a89886c](https://github.com/windmill-labs/windmill/commit/a89886c46a3c1866715771ba75389f8a42d20a1b)) +* stop hidden session preview tabs from acting on keys ([#12531](https://github.com/windmill-labs/windmill/issues/12531)) ([5bf5ff2](https://github.com/windmill-labs/windmill/commit/5bf5ff28bc4f9d47c4473cd5e71e0ee274dece31)) + +## [1.878.0](https://github.com/windmill-labs/windmill/compare/v1.877.0...v1.878.0) (2026-11-19) + + +### Features + +* **python-client:** retry a GET on 429 and 502-504 with exponential backoff ([#12513](https://github.com/windmill-labs/windmill/issues/12513)) ([1c78f8d](https://github.com/windmill-labs/windmill/commit/1c78f8d7a38e49106adcd236f53c026855924682)) +* show how many resources use each resource type ([#12512](https://github.com/windmill-labs/windmill/issues/12512)) ([1fa8fd0](https://github.com/windmill-labs/windmill/commit/1fa8fd0c94cd59eb2330a18e6afc1b56d8e1ed6c)) + + +### Bug Fixes + +* **api:** encode non-ASCII filenames in S3 Content-Disposition ([#9634](https://github.com/windmill-labs/windmill/issues/9634)) ([52b7625](https://github.com/windmill-labs/windmill/commit/52b7625bdff32147fb187289c37db821ee4e0b7c)) +* **api:** type /scripts/list response as ListableScript ([#9577](https://github.com/windmill-labs/windmill/issues/9577)) ([f3b31b1](https://github.com/windmill-labs/windmill/commit/f3b31b18f5f22dbc5de65be562b167e7f2db0b35)) +* **csharp-parser:** mark parameters with a default value as optional ([#10185](https://github.com/windmill-labs/windmill/issues/10185)) ([0659b8a](https://github.com/windmill-labs/windmill/commit/0659b8a12502955ebd78c261f12a6a8bbed03abc)) +* enable DynSelect fields in the schedule editor ([#9718](https://github.com/windmill-labs/windmill/issues/9718)) ([2ceeff3](https://github.com/windmill-labs/windmill/commit/2ceeff3e9cf0bae1b5b87ffe02d158baf85bf119)) +* **frontend:** download a large file result as its file, not as JSON ([#12507](https://github.com/windmill-labs/windmill/issues/12507)) ([905a92a](https://github.com/windmill-labs/windmill/commit/905a92ab32a45b694b99dd60bb0f0244a20ed2e7)) +* preserve object-store config when switching storage tabs ([#9696](https://github.com/windmill-labs/windmill/issues/9696)) ([c11123d](https://github.com/windmill-labs/windmill/commit/c11123db37ee21238311845992777a010b3b408d)) +* put a saved input's name back when its rename is cancelled ([#12483](https://github.com/windmill-labs/windmill/issues/12483)) ([2b8a079](https://github.com/windmill-labs/windmill/commit/2b8a0790a0a973240ca32c5fba0a23339fc21fda)) +* surface backend preview logs in AI eval failures ([#9383](https://github.com/windmill-labs/windmill/issues/9383)) ([7f8765c](https://github.com/windmill-labs/windmill/commit/7f8765c171f941ae9d18af8f8f99949ea9dccdce)) + +## [1.877.0](https://github.com/windmill-labs/windmill/compare/v1.876.1...v1.877.0) (2026-11-18) + + +### Features + +* adapt workspace settings to narrow layouts ([#12492](https://github.com/windmill-labs/windmill/issues/12492)) ([0c18bdc](https://github.com/windmill-labs/windmill/commit/0c18bdc8256c2508341683c69874bbfbbec9daa8)) +* get an approval step's detail by flow run id and step id ([#12521](https://github.com/windmill-labs/windmill/issues/12521)) ([39cb251](https://github.com/windmill-labs/windmill/commit/39cb251ab8639eccf77fd988ff110133309082be)) +* label for-loop iterations with a per-iteration expression ([#12526](https://github.com/windmill-labs/windmill/issues/12526)) ([91de725](https://github.com/windmill-labs/windmill/commit/91de7252b8b82f397c8f7afca023ed54010e219d)) +* offer the hub to compose roles that have code ([#12518](https://github.com/windmill-labs/windmill/issues/12518)) ([306f38d](https://github.com/windmill-labs/windmill/commit/306f38dd0446abb16523e49a021135c8aca7a4d7)) +* open shared AI sessions in the app ([#12486](https://github.com/windmill-labs/windmill/issues/12486)) ([b9dc5f2](https://github.com/windmill-labs/windmill/commit/b9dc5f26dbce9078bbec858c0827a5458ee562be)) +* show a flow's continue-on-error failures on its run and status ([#12525](https://github.com/windmill-labs/windmill/issues/12525)) ([71e7d9e](https://github.com/windmill-labs/windmill/commit/71e7d9e440bd17d81f776f03d835a45a76072ea0)) + + +### Bug Fixes + +* disable SAML instead of crashing when its metadata cannot be loaded ([#12528](https://github.com/windmill-labs/windmill/issues/12528)) ([ae178a0](https://github.com/windmill-labs/windmill/commit/ae178a028746dcbcbf2bf65e9dd3ac5d982465ce)) +* explain why a non-admin cannot edit an email trigger's address ([#12503](https://github.com/windmill-labs/windmill/issues/12503)) ([a2c04c2](https://github.com/windmill-labs/windmill/commit/a2c04c2aa83dbc4d0c3343f56776fd8c10264e30)) +* **flows:** show Python examples in approval-step help drawer ([#9498](https://github.com/windmill-labs/windmill/issues/9498)) ([815db30](https://github.com/windmill-labs/windmill/commit/815db30c39ab499905974415464fa12cfea9ddc4)), closes [#6181](https://github.com/windmill-labs/windmill/issues/6181) +* **frontend:** make run-page flow graph scrollable ([#3830](https://github.com/windmill-labs/windmill/issues/3830)) ([#9607](https://github.com/windmill-labs/windmill/issues/9607)) ([b56bb25](https://github.com/windmill-labs/windmill/commit/b56bb252a9347b1ae4541faec1187213b3838bb9)) +* **frontend:** sync eval drawer open state ([#10333](https://github.com/windmill-labs/windmill/issues/10333)) ([64e6142](https://github.com/windmill-labs/windmill/commit/64e6142277aca4a5a5a53c41e383b56ef53b839c)) +* hit the volume cache on Azure and keep a volume's lease through its pull ([#12520](https://github.com/windmill-labs/windmill/issues/12520)) ([97b80ae](https://github.com/windmill-labs/windmill/commit/97b80aef5e82ec94470fb974ee3676ca403065db)) +* keep every owner chip on the trigger lists while one is selected ([#12485](https://github.com/windmill-labs/windmill/issues/12485)) ([49075dc](https://github.com/windmill-labs/windmill/commit/49075dc246f3331bc8d28d803aea941d690a3050)) +* keep the owner filter on variables and resources to that folder or user ([#12495](https://github.com/windmill-labs/windmill/issues/12495)) ([538ee69](https://github.com/windmill-labs/windmill/commit/538ee694459e8ce1552222541f78b3661438d5b6)) +* let a workspace deps push survive a client or proxy timeout ([#12523](https://github.com/windmill-labs/windmill/issues/12523)) ([67165ca](https://github.com/windmill-labs/windmill/commit/67165cabfcd7160ce318ac0401d0ac4bb4cb2478)) +* let non-admins read an admin-approved GitHub App repository ([#12524](https://github.com/windmill-labs/windmill/issues/12524)) ([a718720](https://github.com/windmill-labs/windmill/commit/a718720fd6c97dcbcfdc4fa53d8b42d60a5f145e)) +* move a Map component when its longitude, latitude or zoom is set to 0 ([#12504](https://github.com/windmill-labs/windmill/issues/12504)) ([75905a8](https://github.com/windmill-labs/windmill/commit/75905a821e0586b579d0a0261fcf9fb70e5f9263)) +* open a script's runs from All runs on an older version's page ([#12488](https://github.com/windmill-labs/windmill/issues/12488)) ([3e3d7d1](https://github.com/windmill-labs/windmill/commit/3e3d7d1192a79455d4b1ad7ae534141ebc843cb0)) +* open an older script version without flashing the Archived alert ([#12497](https://github.com/windmill-labs/windmill/issues/12497)) ([3cc2f16](https://github.com/windmill-labs/windmill/commit/3cc2f16dd181ad1f0bc2efee7389fc9dc6e02bc0)) +* read a job's memory peak past its unshare, tini or nsjail wrapper ([#12510](https://github.com/windmill-labs/windmill/issues/12510)) ([258b556](https://github.com/windmill-labs/windmill/commit/258b5564c0d6afe792eca8ade9e4b82ba03c9763)) +* resolve the caller's role capabilities at authentication ([#12501](https://github.com/windmill-labs/windmill/issues/12501)) ([e24a430](https://github.com/windmill-labs/windmill/commit/e24a4309d0020e3acaf823768d368b099bbef6ec)) +* run the pinned version from a flow version's page ([#12505](https://github.com/windmill-labs/windmill/issues/12505)) ([8984bcc](https://github.com/windmill-labs/windmill/commit/8984bccf83e32ab29459d4736a02b0ef89402c25)) +* serve only enabled models on the workspace's configured AI key ([#12527](https://github.com/windmill-labs/windmill/issues/12527)) ([2c7d3fa](https://github.com/windmill-labs/windmill/commit/2c7d3fa98fa650b939f5d761abb0b483b6139d11)) +* show a renamed workspace's new name in the header without a reload ([#12487](https://github.com/windmill-labs/windmill/issues/12487)) ([806f2bf](https://github.com/windmill-labs/windmill/commit/806f2bf735aa25c8c067d2809125d8c96742346f)) +* switch a Select Tab component's tab when its default value changes ([#12494](https://github.com/windmill-labs/windmill/issues/12494)) ([e1ac1fd](https://github.com/windmill-labs/windmill/commit/e1ac1fddf6f6b9bf440c9e157a6309f77f65c7fa)) +* **worker:** send SIGINT/SIGTERM to job process group on cancel/timeout ([#12522](https://github.com/windmill-labs/windmill/issues/12522)) ([3bf2088](https://github.com/windmill-labs/windmill/commit/3bf208829050309f0efd27b6c335b1dd529e80a7)) + +## [1.876.1](https://github.com/windmill-labs/windmill/compare/v1.876.0...v1.876.1) (2026-11-17) + + +### Bug Fixes + +* build enterprise features with systemstat 0.2.8 ([#12484](https://github.com/windmill-labs/windmill/issues/12484)) ([7573399](https://github.com/windmill-labs/windmill/commit/7573399bbc8da8d3e85de1f26f17b6e4f9c60636)) +* let the trigger list search find a trigger by its route, URL or address ([#12489](https://github.com/windmill-labs/windmill/issues/12489)) ([18d0a78](https://github.com/windmill-labs/windmill/commit/18d0a78bb766dde058525ea3b8afb3fa5727b9b5)) +* move a Range component's upper handle when its default high changes ([#12491](https://github.com/windmill-labs/windmill/issues/12491)) ([9ddb88f](https://github.com/windmill-labs/windmill/commit/9ddb88f043810a574d0adde001c1a6f97a3d4c96)) +* route a null dynamic tag input to the default tag instead of a queue named null ([#12499](https://github.com/windmill-labs/windmill/issues/12499)) ([52658af](https://github.com/windmill-labs/windmill/commit/52658af01d9f59c325ed2a659388552be0a6f7c5)) + +## [1.876.0](https://github.com/windmill-labs/windmill/compare/v1.875.0...v1.876.0) (2026-11-17) + + +### Features + +* let AI harnesses solve tasks with code, then save and reuse it ([#12472](https://github.com/windmill-labs/windmill/issues/12472)) ([caddc3f](https://github.com/windmill-labs/windmill/commit/caddc3f4ad3aa47b8ee7b2598a1ede8ae7a3400c)) +* pin the current turn's user message at the top of session chat ([#12468](https://github.com/windmill-labs/windmill/issues/12468)) ([c204232](https://github.com/windmill-labs/windmill/commit/c204232609ab0ebdbfe55f4b4711e04652de3fd9)) + + +### Bug Fixes + +* check new hub paths when a trigger or schedule is saved ([#12465](https://github.com/windmill-labs/windmill/issues/12465)) ([88ef4e9](https://github.com/windmill-labs/windmill/commit/88ef4e9f3c1549f031084767d747ac45bedf1c99)) +* default the path picker to a folder the user can write to ([#12448](https://github.com/windmill-labs/windmill/issues/12448)) ([aef5332](https://github.com/windmill-labs/windmill/commit/aef5332f9563cc1540d93fbd04d8ccaa85a8f10f)) +* do not treat a folder or user with a longer name as writable ([#12450](https://github.com/windmill-labs/windmill/issues/12450)) ([8c4d83c](https://github.com/windmill-labs/windmill/commit/8c4d83c5e7b4cd8ce83f90185afaceec2dc5f545)) +* drop runs-page rows of queued jobs that completed as skipped ([#12470](https://github.com/windmill-labs/windmill/issues/12470)) ([364e729](https://github.com/windmill-labs/windmill/commit/364e729a08ac6540b688d15c0171910100dbd481)) +* encode the webhook GET payload as UTF-8 so non-ASCII arguments work ([#12453](https://github.com/windmill-labs/windmill/issues/12453)) ([2cb29f8](https://github.com/windmill-labs/windmill/commit/2cb29f87a027fdd4bb6c3fd2e1fd900af65cacb1)) +* escape single quotes in the webhook curl example body ([#12454](https://github.com/windmill-labs/windmill/issues/12454)) ([b76af45](https://github.com/windmill-labs/windmill/commit/b76af459bbb3b9e726b433e06aa6a4a600de49ab)) +* judge session editor rights in the session's workspace ([#12462](https://github.com/windmill-labs/windmill/issues/12462)) ([dd1c8fe](https://github.com/windmill-labs/windmill/commit/dd1c8fe66d3b7d1b340856ba4d55af8de07a787e)) +* keep underscores and hyphens inside words in description previews ([#12449](https://github.com/windmill-labs/windmill/issues/12449)) ([57268b6](https://github.com/windmill-labs/windmill/commit/57268b661643132ca2b7c917ac28bc2d765a7238)) +* let a folder's creator manage it from the folders page without a reload ([#12445](https://github.com/windmill-labs/windmill/issues/12445)) ([465446e](https://github.com/windmill-labs/windmill/commit/465446e1ba83504e0d675e3fd2e2a15424742962)) +* let a folder's creator own it right after creating it in the path picker ([#12447](https://github.com/windmill-labs/windmill/issues/12447)) ([96c97b0](https://github.com/windmill-labs/windmill/commit/96c97b0cdb921777856186178e303dd701234310)) +* **py-parser:** read docstring Args descriptions for async def main ([#12473](https://github.com/windmill-labs/windmill/issues/12473)) ([2351bc8](https://github.com/windmill-labs/windmill/commit/2351bc8a30e00190dd928ed8b37a6b16372272bb)) +* **python-client:** omit approver from get_resume_urls when not given ([#12446](https://github.com/windmill-labs/windmill/issues/12446)) ([bbb48f5](https://github.com/windmill-labs/windmill/commit/bbb48f5a61c9d23ba541fdcfa3d198a72937d71f)) +* **python:** back S3BufferedReader with a real BufferedReader ([#12456](https://github.com/windmill-labs/windmill/issues/12456)) ([9a074b1](https://github.com/windmill-labs/windmill/commit/9a074b1c73c83ffc10e1d00b94337f55ae9ff2f1)) +* read agent tool inputs from the flow running the agent step ([#12457](https://github.com/windmill-labs/windmill/issues/12457)) ([dd9f633](https://github.com/windmill-labs/windmill/commit/dd9f633764bcef0451eb3fb3580389a91dfa99ad)) +* refresh a group's members on the Groups page after saving it ([#12460](https://github.com/windmill-labs/windmill/issues/12460)) ([428a07f](https://github.com/windmill-labs/windmill/commit/428a07f5fc4d894d316a6c6aefcd859c91d0e2ee)) +* refresh the schedule's upcoming events when the timezone changes ([#12459](https://github.com/windmill-labs/windmill/issues/12459)) ([938c03c](https://github.com/windmill-labs/windmill/commit/938c03c501ff9fc47152c06b8f6dddc9912d59b5)) +* save a cleared variable value instead of keeping the old one ([#12466](https://github.com/windmill-labs/windmill/issues/12466)) ([bd266bc](https://github.com/windmill-labs/windmill/commit/bd266bc3baab90393de40531fb140e7bcbea0ebc)) + + +### Performance Improvements + +* mount only the tail of a chat transcript, older messages on scroll ([#12469](https://github.com/windmill-labs/windmill/issues/12469)) ([17a56db](https://github.com/windmill-labs/windmill/commit/17a56db9ea51a5befe61d5c216ceedd481d835b6)) + +## [1.875.0](https://github.com/windmill-labs/windmill/compare/v1.874.0...v1.875.0) (2026-11-14) + + +### Features + +* exact start and end of a fairness cap in its alerts ([#12438](https://github.com/windmill-labs/windmill/issues/12438)) ([df0e5cf](https://github.com/windmill-labs/windmill/commit/df0e5cf4c2e90e071594f962cb1c5ed9e9023754)) +* fairness reserve as a worker group setting, shown on the workers page ([#12435](https://github.com/windmill-labs/windmill/issues/12435)) ([5f8e002](https://github.com/windmill-labs/windmill/commit/5f8e0022b699f58836d1a24304debcc7d7611e1a)) +* show long step durations in hours and minutes on run timelines ([#12437](https://github.com/windmill-labs/windmill/issues/12437)) ([c6955ed](https://github.com/windmill-labs/windmill/commit/c6955ed4457c2bdb59fd3ffef4379ce05548c999)) + + +### Bug Fixes + +* keep shortcuts from opening home filters over global search ([#12439](https://github.com/windmill-labs/windmill/issues/12439)) ([d09336d](https://github.com/windmill-labs/windmill/commit/d09336d8df1814434d219e732421d2358e485890)) + +## [1.874.0](https://github.com/windmill-labs/windmill/compare/v1.873.1...v1.874.0) (2026-11-14) + + +### Features + +* fairness reserve workers that only serve non-overloaded workspaces ([#12431](https://github.com/windmill-labs/windmill/issues/12431)) ([df56c11](https://github.com/windmill-labs/windmill/commit/df56c111bb597bc9d3f99462c5d40e1b57e60def)) +* fairness-aware queue alerts and a capped-workspace alert ([#12432](https://github.com/windmill-labs/windmill/issues/12432)) ([9724f3b](https://github.com/windmill-labs/windmill/commit/9724f3bdf085c68e1b91c9655cbe01c3f2598bdd)) + + +### Bug Fixes + +* keep group run-as principals when renaming a group-* member ([#12409](https://github.com/windmill-labs/windmill/issues/12409)) ([fffef91](https://github.com/windmill-labs/windmill/commit/fffef918881ed5b098ac5552d6d9094950963e3a)) +* move handler paths when renaming or offboarding a user ([#12420](https://github.com/windmill-labs/windmill/issues/12420)) ([161ab6f](https://github.com/windmill-labs/windmill/commit/161ab6f581b2ea97f45812a903ae2fbebddc4184)) + +## [1.873.1](https://github.com/windmill-labs/windmill/compare/v1.873.0...v1.873.1) (2026-11-13) + + +### Bug Fixes + +* keep static input references in raw-app source deploy policies ([#12428](https://github.com/windmill-labs/windmill/issues/12428)) ([a64dc9a](https://github.com/windmill-labs/windmill/commit/a64dc9a5605dc297f28f8f7afd15e06fc9d17ce3)) +* keep step_id, job_id, flow_path and extra on dedicated worker errors ([#12417](https://github.com/windmill-labs/windmill/issues/12417)) ([3b860d5](https://github.com/windmill-labs/windmill/commit/3b860d549e3819f6a849704737742b6c00377252)) +* revoke api tokens and mcp oauth grants on leave_instance ([#12430](https://github.com/windmill-labs/windmill/issues/12430)) ([2c39bf0](https://github.com/windmill-labs/windmill/commit/2c39bf044a04ca20f2f076ecc79d64f341f35261)) +* run dedicated flow script steps on their runners ([#12419](https://github.com/windmill-labs/windmill/issues/12419)) ([f738a4b](https://github.com/windmill-labs/windmill/commit/f738a4bad4e211ded0a39d48722544f9321e0190)) + +## [1.873.0](https://github.com/windmill-labs/windmill/compare/v1.872.0...v1.873.0) (2026-11-13) + + +### Features + +* show session status or unread count on the folded AI sessions section ([#12351](https://github.com/windmill-labs/windmill/issues/12351)) ([16fe0b2](https://github.com/windmill-labs/windmill/commit/16fe0b2e7450ddfe8bf9a101dbf6d414c5ed0405)) +* vertex_ai_federated resource type for workload identity federation ([#12416](https://github.com/windmill-labs/windmill/issues/12416)) ([c93a173](https://github.com/windmill-labs/windmill/commit/c93a17396c818b04951940e324057c8b8ae03a3c)) + + +### Bug Fixes + +* keep the (edit) suffix visible on truncated session tabs ([#12384](https://github.com/windmill-labs/windmill/issues/12384)) ([18224a2](https://github.com/windmill-labs/windmill/commit/18224a2cd86fe84421e8e5a51112a46db900bcd5)) +* stop logging credential-bearing instance setting values ([#12413](https://github.com/windmill-labs/windmill/issues/12413)) ([b2793f2](https://github.com/windmill-labs/windmill/commit/b2793f2aca67c650fd7f41d273f4b21761f903c5)) + +## [1.872.0](https://github.com/windmill-labs/windmill/compare/v1.871.1...v1.872.0) (2026-11-13) + + +### Features + +* background tools for ai agent steps ([#11827](https://github.com/windmill-labs/windmill/issues/11827)) ([10a8577](https://github.com/windmill-labs/windmill/commit/10a8577fab558d4c76cc7526a6a4c63bee9040e8)) +* clarify OAuth connect levels and client credential sharing ([#11820](https://github.com/windmill-labs/windmill/issues/11820)) ([59a8657](https://github.com/windmill-labs/windmill/commit/59a8657426419c6734bc1e6e65c201c5c7309b9a)) +* mount volumes read-only without the exclusive lease ([#12410](https://github.com/windmill-labs/windmill/issues/12410)) ([70711be](https://github.com/windmill-labs/windmill/commit/70711bec68915ecea06834c356957cf3ffdd40cd)) +* one turn per memory id, a new message takes over a parked turn ([#11831](https://github.com/windmill-labs/windmill/issues/11831)) ([792e66a](https://github.com/windmill-labs/windmill/commit/792e66a30a5d90cb574300225e3f2f404b9165c8)) + + +### Bug Fixes + +* drop the unreachable oneshot map_err rejected by rustc 1.100 ([#12407](https://github.com/windmill-labs/windmill/issues/12407)) ([1645285](https://github.com/windmill-labs/windmill/commit/164528563dd2de4b294b29bbd807b2b3e86b5c52)) +* stop backend-test rust cache from bloating and filling the runner disk ([#12411](https://github.com/windmill-labs/windmill/issues/12411)) ([bc613cf](https://github.com/windmill-labs/windmill/commit/bc613cf41d41f61631c9ae999fc8d10cf3c8813a)) + +## [1.871.1](https://github.com/windmill-labs/windmill/compare/v1.871.0...v1.871.1) (2026-11-12) + + +### Bug Fixes + +* remove dangling cli/cursor symlink that breaks release builds ([#12405](https://github.com/windmill-labs/windmill/issues/12405)) ([5b00012](https://github.com/windmill-labs/windmill/commit/5b00012ec43fc577fd8e5376f8e3ade03e44ecac)) + +## [1.871.0](https://github.com/windmill-labs/windmill/compare/v1.870.0...v1.871.0) (2026-11-12) + + +### Features + +* bring ai agents in line with scripts and flows ([#12311](https://github.com/windmill-labs/windmill/issues/12311)) ([162c6e4](https://github.com/windmill-labs/windmill/commit/162c6e4da6afb68961b7fa7cfc35642d8d890d57)) +* move the home tree's owner menu to the row's right side ([#12359](https://github.com/windmill-labs/windmill/issues/12359)) ([67cfa46](https://github.com/windmill-labs/windmill/commit/67cfa4630f866afa5cc98dc5a26a880d596bdc0a)) +* open the AI chat run card full screen ([#12392](https://github.com/windmill-labs/windmill/issues/12392)) ([38000fa](https://github.com/windmill-labs/windmill/commit/38000fa504cb38dce490cd41a69c0e7e580e367d)) +* show a loading skeleton for the sidebar session list ([#12383](https://github.com/windmill-labs/windmill/issues/12383)) ([f004da9](https://github.com/windmill-labs/windmill/commit/f004da9269eb6ce17003dec0259c2287f4d21201)) +* show key hints on the queued chip and send it mid-turn ([#12342](https://github.com/windmill-labs/windmill/issues/12342)) ([63190ef](https://github.com/windmill-labs/windmill/commit/63190ef61c9eb3c1ecbdf74581c8a56659636492)) + + +### Bug Fixes + +* hold a builder's hub steps to the run-time hub rule ([#12401](https://github.com/windmill-labs/windmill/issues/12401)) ([6f52126](https://github.com/windmill-labs/windmill/commit/6f521263775526edd66ca69219edd2b097bd9f46)) +* hold roles that cannot run to read-only over mcp and the ai session ([#12357](https://github.com/windmill-labs/windmill/issues/12357)) ([2994e06](https://github.com/windmill-labs/windmill/commit/2994e0664347b63d03d1281a6e16a62c7c91b798)) +* refuse a hub path named by a member without the code capability ([#12381](https://github.com/windmill-labs/windmill/issues/12381)) ([260b480](https://github.com/windmill-labs/windmill/commit/260b480df6418dede84fbab50a19d12d1bc6f221)) +* stream agent results as markdown with openable tool calls ([#12394](https://github.com/windmill-labs/windmill/issues/12394)) ([b6570af](https://github.com/windmill-labs/windmill/commit/b6570af11a21625dac5620655ee1aaacf9250dd6)) + +## [1.870.0](https://github.com/windmill-labs/windmill/compare/v1.869.0...v1.870.0) (2026-11-12) + + +### Features + +* charts and tables in AI chat replies and artifacts ([#12374](https://github.com/windmill-labs/windmill/issues/12374)) ([6ba4002](https://github.com/windmill-labs/windmill/commit/6ba400239b8422132fcd4a23b684dfe878f477e4)) +* run the git sync pull request diff check from auto-pull polling ([#12360](https://github.com/windmill-labs/windmill/issues/12360)) ([6e6789a](https://github.com/windmill-labs/windmill/commit/6e6789a5f13857ba690542966dbc7929d8c3dfc8)) + + +### Bug Fixes + +* apply the url/embed toggle to every app link, jwt ones included ([#12378](https://github.com/windmill-labs/windmill/issues/12378)) ([f634330](https://github.com/windmill-labs/windmill/commit/f634330efbdde5771ee7311324b634b3ae34a1a9)) +* **cli:** pull datatable migrations on Windows ([#12380](https://github.com/windmill-labs/windmill/issues/12380)) ([8e73d30](https://github.com/windmill-labs/windmill/commit/8e73d30d6a3d14d4a5155adf236c85132296ab75)) +* declare es2023 lib the frontend already relies on ([#12372](https://github.com/windmill-labs/windmill/issues/12372)) ([37538e9](https://github.com/windmill-labs/windmill/commit/37538e979e5de682ab090d7c2c5a713ca466bddb)) +* limit cancel-all-matching-filters to top-level jobs ([#12373](https://github.com/windmill-labs/windmill/issues/12373)) ([3e7adc1](https://github.com/windmill-labs/windmill/commit/3e7adc1c4fc93e747d2644be24060f45eba07644)) +* report a failed mcp script or flow run as a tool error ([#12365](https://github.com/windmill-labs/windmill/issues/12365)) ([354aa25](https://github.com/windmill-labs/windmill/commit/354aa2581dcbccfe67781a269f92fc7693bf4456)) +* show the external JWT embed URL for members apps ([#12377](https://github.com/windmill-labs/windmill/issues/12377)) ([78ca426](https://github.com/windmill-labs/windmill/commit/78ca4263ee586b3c5afd5a4224c9180cfd6fb6a2)) +* skip the worker's suspend_resume audit row when a rejected approval continues ([#12376](https://github.com/windmill-labs/windmill/issues/12376)) ([d4f9975](https://github.com/windmill-labs/windmill/commit/d4f9975121ad8c84726a9f8ecf59d844fd0bf245)) +* truncate long labels in chat tool call headers ([#12366](https://github.com/windmill-labs/windmill/issues/12366)) ([d033939](https://github.com/windmill-labs/windmill/commit/d0339396efdfd40cd53e70024b37c6847064cd36)) + +## [1.869.0](https://github.com/windmill-labs/windmill/compare/v1.868.0...v1.869.0) (2026-11-12) + + +### Features + +* move a live ai session into a workspace fork with its drafts ([#11602](https://github.com/windmill-labs/windmill/issues/11602)) ([484a769](https://github.com/windmill-labs/windmill/commit/484a7699dbd4ecf827528030c8f8bfdc0d9c483b)) +* restyle artifact documents and add an html download ([#12355](https://github.com/windmill-labs/windmill/issues/12355)) ([addc644](https://github.com/windmill-labs/windmill/commit/addc644c1c6e167a436436b2ecb77728f1b4ae21)) +* run AI decision steps on Gemini's Decisions API ([#12370](https://github.com/windmill-labs/windmill/issues/12370)) ([e9f4636](https://github.com/windmill-labs/windmill/commit/e9f4636d445d17b73b3b32aa03b88667694fe13c)) + + +### Bug Fixes + +* **cli:** point wmill.yaml schema header at an absolute, release-pinned URL ([#12367](https://github.com/windmill-labs/windmill/issues/12367)) ([9eb3d2e](https://github.com/windmill-labs/windmill/commit/9eb3d2e7d480608739f6e5c8dbc1cf75e0bb4243)) +* keep favorites when forking a workspace ([#12325](https://github.com/windmill-labs/windmill/issues/12325)) ([97dedc2](https://github.com/windmill-labs/windmill/commit/97dedc2f10a1d1fcf6bf3b93accc0a9b53fea5d5)) +* keep the picked data table when starting a raw app in the editor ([#12328](https://github.com/windmill-labs/windmill/issues/12328)) ([b4df6ef](https://github.com/windmill-labs/windmill/commit/b4df6ef8330892c891f31d6614aa0df993c0ad21)) +* move schedule and trigger run-as when renaming a user ([#12368](https://github.com/windmill-labs/windmill/issues/12368)) ([1583207](https://github.com/windmill-labs/windmill/commit/1583207af74522adac9e4c1f3bd78e554cd7af2d)) +* run ci tests once a batch deploy has landed, not per item ([#12369](https://github.com/windmill-labs/windmill/issues/12369)) ([bd5f4d4](https://github.com/windmill-labs/windmill/commit/bd5f4d4d3dfa9c283e32bf6bd78209406c217145)) +* **rust-client:** tolerate new api fields in wait_job and set_resource ([#12353](https://github.com/windmill-labs/windmill/issues/12353)) ([f028858](https://github.com/windmill-labs/windmill/commit/f0288586e3706d1eb5400e7b5433385c4d4b2ea8)) +* use the slim scrollbar in the homepage recent runs card ([#12362](https://github.com/windmill-labs/windmill/issues/12362)) ([0491ccf](https://github.com/windmill-labs/windmill/commit/0491ccf3eb30d2dea1b11c4bb02d627ab6c1b683)) + +## [1.868.0](https://github.com/windmill-labs/windmill/compare/v1.867.0...v1.868.0) (2026-11-11) + + +### Features + +* compile tailwind css v4 in raw app bundles ([#12346](https://github.com/windmill-labs/windmill/issues/12346)) ([18556fd](https://github.com/windmill-labs/windmill/commit/18556fd9b897e2de6cd95f060d630bc41d7230aa)) + + +### Bug Fixes + +* back off job polling to 2s after 100 polls ([#12344](https://github.com/windmill-labs/windmill/issues/12344)) ([abede3a](https://github.com/windmill-labs/windmill/commit/abede3a02978f4c65c9c018b27a4167fd31feac2)) +* bump cli bundled minimatch, yaml and fast-uri past advisories ([#12337](https://github.com/windmill-labs/windmill/issues/12337)) ([f7f2eee](https://github.com/windmill-labs/windmill/commit/f7f2eeedfd16a64a462a58b51b81119eb102735c)) +* carry every compared field through fork deploy and diff ([#12348](https://github.com/windmill-labs/windmill/issues/12348)) ([f9cf596](https://github.com/windmill-labs/windmill/commit/f9cf596b3cee77e0070e2decda5cbab259b10471)) +* force the structured output tool on claude 3 and 4 again ([#12349](https://github.com/windmill-labs/windmill/issues/12349)) ([9c76c79](https://github.com/windmill-labs/windmill/commit/9c76c79789dbb7093aa18c4a84404da4cdde967c)) +* hide your own empty user space with the hide empty folders option ([#12345](https://github.com/windmill-labs/windmill/issues/12345)) ([d37dcca](https://github.com/windmill-labs/windmill/commit/d37dcca4c6d8dfdfb52cf96e2b36fbab32896e5a)) +* keep the runs list scrollbar and column labels unclipped ([#12347](https://github.com/windmill-labs/windmill/issues/12347)) ([d1e97ef](https://github.com/windmill-labs/windmill/commit/d1e97ef0206fd013a2576223401bf2a907f72290)) +* treat skipped jobs as successful in result and wait paths ([#12340](https://github.com/windmill-labs/windmill/issues/12340)) ([9d9875c](https://github.com/windmill-labs/windmill/commit/9d9875cf0e7bc85f62d1084529012e92c192a253)) + + +### Performance Improvements + +* build the ee debug file in the same depot build as the image ([#12339](https://github.com/windmill-labs/windmill/issues/12339)) ([2688493](https://github.com/windmill-labs/windmill/commit/2688493736dc5359857db7bc229749fdda676b60)) + +## [1.867.0](https://github.com/windmill-labs/windmill/compare/v1.866.0...v1.867.0) (2026-11-10) + + +### Features + +* fold sidebar AI chats and sessions inactive for over a week ([#12314](https://github.com/windmill-labs/windmill/issues/12314)) ([466885f](https://github.com/windmill-labs/windmill/commit/466885fd26b74bd20de67ee0ef0e55a47826cd47)) +* gate public apps on cloud plans and unpublish them on archive ([#12321](https://github.com/windmill-labs/windmill/issues/12321)) ([a9f5a9c](https://github.com/windmill-labs/windmill/commit/a9f5a9caa0bce2162a34bca1cfd0438893945d6e)) +* reveal the failed call from a tool group's failed badge ([#12320](https://github.com/windmill-labs/windmill/issues/12320)) ([0e1464e](https://github.com/windmill-labs/windmill/commit/0e1464e877dcfabdffc8901d2a0735e04b73772e)) + + +### Bug Fixes + +* build Azure block upload URLs from the account endpoint ([#12333](https://github.com/windmill-labs/windmill/issues/12333)) ([38e7463](https://github.com/windmill-labs/windmill/commit/38e7463dd4e93c36f28fefb102bc5d0d3060cdf3)) +* cut long item summaries in the session composer placeholder ([#12312](https://github.com/windmill-labs/windmill/issues/12312)) ([abfa6b1](https://github.com/windmill-labs/windmill/commit/abfa6b1a6743d99858b6923f40a76deb9e6ff063)) +* drop renamed and deleted items from Home recent list ([#12317](https://github.com/windmill-labs/windmill/issues/12317)) ([c144738](https://github.com/windmill-labs/windmill/commit/c1447389e546022f1fb6cd2a18c88480e27ce792)) +* explain why a fork folder deploy can leave a lasting conflict ([#12323](https://github.com/windmill-labs/windmill/issues/12323)) ([6a11d30](https://github.com/windmill-labs/windmill/commit/6a11d3033ad329a730848698d9fa8ddd2cb5563e)) +* keep siblings in place when editing an EditableInput ([#12318](https://github.com/windmill-labs/windmill/issues/12318)) ([5e89ba1](https://github.com/windmill-labs/windmill/commit/5e89ba180e57922a107d840e9fe2b8c00fb2340a)) +* keep the sessions sidebar icons stable until the workspace list loads ([#12322](https://github.com/windmill-labs/windmill/issues/12322)) ([9d7adef](https://github.com/windmill-labs/windmill/commit/9d7adefe23f130168e7e9d77ce4a52c4c4f2223f)) +* load mermaid diagrams without source flashes or layout jumps ([#12319](https://github.com/windmill-labs/windmill/issues/12319)) ([fecc8a6](https://github.com/windmill-labs/windmill/commit/fecc8a6bfd01dacea90bee6d9864527d26cf1714)) +* mark delete and discard tool confirmations as destructive ([#12324](https://github.com/windmill-labs/windmill/issues/12324)) ([949ef23](https://github.com/windmill-labs/windmill/commit/949ef234a841dd18eca661addbf2369329dbc9a3)) +* name agents in session chat tool call labels ([#12313](https://github.com/windmill-labs/windmill/issues/12313)) ([80e2be5](https://github.com/windmill-labs/windmill/commit/80e2be56ddd21cd7f5ea778989e83e09e87b08f5)) +* **python:** give folder modules an empty __path__ so relative imports resolve to workspace scripts ([#12307](https://github.com/windmill-labs/windmill/issues/12307)) ([0323310](https://github.com/windmill-labs/windmill/commit/0323310d6455c361eef2ca857883cdfd888c43ce)) +* read dedicated worker entries with the runnable parser ([#12326](https://github.com/windmill-labs/windmill/issues/12326)) ([df6a61c](https://github.com/windmill-labs/windmill/commit/df6a61c07eabb9845b7ba5a3ef7284df52517445)) +* send AI session requests with their own workspace's AI config ([#12330](https://github.com/windmill-labs/windmill/issues/12330)) ([e8d48b1](https://github.com/windmill-labs/windmill/commit/e8d48b1348893e9396734d0ed4fc4d33049fb0ed)) +* stop forcing the structured output tool for Claude AI agents ([#12331](https://github.com/windmill-labs/windmill/issues/12331)) ([5b4f918](https://github.com/windmill-labs/windmill/commit/5b4f918e0d7742bf09629f0cfe8f90b3038f965e)) +* stream logs of a selected step nested in a subflow or loop ([#12334](https://github.com/windmill-labs/windmill/issues/12334)) ([841cc3e](https://github.com/windmill-labs/windmill/commit/841cc3ecbad7e599086bdb2902fa8c2d4c48e7a6)) +* tighten forwarded http trigger headers and route resolution ([#12298](https://github.com/windmill-labs/windmill/issues/12298)) ([c3adae1](https://github.com/windmill-labs/windmill/commit/c3adae14017cb81cf15549c3f2000eba65e424c0)) +* **worker:** wait up to 3 min for migrations before exiting ([#12316](https://github.com/windmill-labs/windmill/issues/12316)) ([a2685ef](https://github.com/windmill-labs/windmill/commit/a2685ef71880aa9d9745709e5b57f29ff76a85e0)) + + +### Performance Improvements + +* cut release CI wall time and build windmill-extra on its own release ([#12329](https://github.com/windmill-labs/windmill/issues/12329)) ([7ec64ab](https://github.com/windmill-labs/windmill/commit/7ec64ab33acc56870975c05f24a983bdcd146ee2)) + ## [1.866.0](https://github.com/windmill-labs/windmill/compare/v1.865.0...v1.866.0) (2026-11-10) diff --git a/CONTEXT.md b/CONTEXT.md index f015fff0a4..b6445d9fd2 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -39,9 +39,15 @@ _Avoid_: JS field, code input ### Flow chat +**Agent**: +A saved AI agent: an `ai_agent` resource holding a model, prompt and tools. Flow steps link to +it, and it also runs on its own (its page, the API, Slack, apps) as a one-step flow, so it has +conversations of its own. See `docs/reusable-ai-agents.md`. +_Avoid_: bot, assistant + **Conversation**: -One thread of messages against one chat-enabled flow, with its own agent memory. A flow has -many; the chat shows one at a time. +One thread of messages against one chat-enabled flow or one agent, with its own agent memory. +Each has many; the chat shows one at a time. _Avoid_: thread, session (that names an AI session, a different thing), chat (that names the surface) **Turn**: diff --git a/Dockerfile b/Dockerfile index 9072838c4d..32afc8347f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ ARG DEBIAN_IMAGE=debian:trixie-slim ARG RUST_IMAGE=rust:1.97-slim-trixie # NOTE: If changing, also change go version in workspace dependencies template at WorkspaceDependenciesEditor.svelte -ARG GO_VERSION=1.27.3 +ARG GO_VERSION=1.27.4 # crane is built from source rather than downloaded: its release binaries are built with whatever # Go was current at release time, so their stdlib lags behind the Go the image installs. @@ -180,7 +180,7 @@ ENV PATH /usr/local/bin:/root/.local/bin:/tmp/.local/bin:$PATH # The build cache keeps the apt layer while the base image digest and this line are unchanged, so # Debian security updates are not picked up by later builds. Bump to force a fresh apt-get upgrade; # bump it in docker/DockerfileSlim and docker/DockerfileSlimEe too. -ARG APT_REFRESH=1 +ARG APT_REFRESH=2 RUN echo "apt refresh ${APT_REFRESH}" \ && apt-get update \ && apt-get upgrade -y \ @@ -276,7 +276,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.13.6/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.8/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 @@ -335,7 +335,7 @@ COPY --from=builder /windmill/target/release/windmill ${APP}/windmill # 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.4 /usr/local/bin/bun /usr/bin/bun +COPY --from=oven/bun:1.4.5 /usr/local/bin/bun /usr/bin/bun # Install windmill CLI RUN bun install -g windmill-cli \ diff --git a/README.md b/README.md index df877e2c0f..b7505151d3 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ See [let business teams build with AI safely](https://www.windmill.dev/docs/adva ## Main Concepts -1. Define a minimal and generic script in Python, TypeScript, Go or Bash that solves a specific task. The code can be defined in the provided Web IDE or synchronized with your own GitHub repo (e.g. through VS Code extension): [provided Web IDE](https://www.windmill.dev/docs/code_editor) or [synchronized with your own GitHub repo](https://www.windmill.dev/docs/advanced/cli/sync) (e.g. through [VS Code](https://www.windmill.dev/docs/cli_local_dev/vscode-extension) extension): +1. Define a minimal and generic script in Python, TypeScript, Go or Bash that solves a specific task. The code can be defined in the [provided Web IDE](https://www.windmill.dev/docs/code_editor) or [synchronized with your own GitHub repo](https://www.windmill.dev/docs/advanced/cli/sync) (e.g. through [VS Code](https://www.windmill.dev/docs/cli_local_dev/vscode-extension) extension): ![Step 1](./imgs/windmill-editor.png) diff --git a/ai_evals/cases/cli.yaml b/ai_evals/cases/cli.yaml index fdf469130d..c548dafbd9 100644 --- a/ai_evals/cases/cli.yaml +++ b/ai_evals/cases/cli.yaml @@ -253,3 +253,25 @@ - does not modify the workspace - recommends generate-metadata before sync push - presents the commands in order + +# Code mode from the CLI: a task against a system the workspace holds credentials for is answered +# by previewing a script in the user's scope, never by pushing it. `wmill` is stubbed here, so the +# preview is checked as a proposed command and the file as written. +- id: cli-codemode-preview-not-push + prompt: |- + How many stars does windmill-labs/windmill have on GitHub right now? Use our GitHub resource + at `f/evals/github_main` in the Windmill workspace. + cliExpect: + requiredSkills: + - code-mode + requiredProposedCommands: + - wmill script preview + forbiddenProposedCommands: + - wmill sync push + forbiddenExecutedCommands: + - ^wmill sync push + judgeChecklist: + - writes one Windmill script with a main function that returns the repository's star count, for a u// path (`wmill` is stubbed here and refuses every command, so a placeholder username, a script given in the reply rather than written once the stub refused, and no count in the reply are all fine) + - the script takes the GitHub resource as a typed main parameter rather than reading a token itself + - proposes running it with wmill script preview, passing $res:f/evals/github_main + - does not push or deploy the script diff --git a/ai_evals/cases/global.yaml b/ai_evals/cases/global.yaml index b258c3822a..79da75eed1 100644 --- a/ai_evals/cases/global.yaml +++ b/ai_evals/cases/global.yaml @@ -4080,3 +4080,162 @@ skipJudge: true judgeChecklist: - explains the MCP setup from the docs: the MCP URL with a token, added to Claude + +# --- Charts and tables in replies (```wm-display blocks) --- +# The chat renders a ```wm-display block holding a chart or table value; anything the catalog +# rejects shows as code with an error. Pin that the model reaches for it when a chart is the +# answer, that what it writes validates, and that a plain question gets prose. + +- id: global-display-chart-in-reply + prompt: |- + Our deploys last week were Mon 4, Tue 7, Wed 3, Thu 9, Fri 6. Can you chart that for me? + runtime: + maxTurns: 6 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + - delete_workspace_item + assistantExpect: + displayBlocks: required + judgeAssistantText: true + judgeChecklist: + - the reply shows the five days' deploy counts as a chart rather than only as text + - the chart carries the values given (Mon 4, Tue 7, Wed 3, Thu 9, Fri 6) + - does not create a script or flow just to draw the chart + +- id: global-display-chart-in-artifact + prompt: |- + Write me a short doc I can share summarizing last month's support tickets by channel: + email 120, chat 85, phone 30, other 12. Include a chart. + runtime: + maxTurns: 8 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - create_artifact + toolCallArgs: + - tool: create_artifact + field: content + stringIncludesAnyOf: + - "```wm-display" + skipJudge: true + judgeChecklist: + - creates an artifact whose content includes a chart of the ticket counts by channel + +- id: global-display-not-for-prose + prompt: |- + What's the difference between a flow and a script in Windmill? + runtime: + maxTurns: 6 + sessionChat: true + validate: + draftCountExactly: 0 + assistantExpect: + displayBlocks: forbidden + skipJudge: true + judgeChecklist: + - answers in prose without a chart or table block + +# --- Code mode: a task done with code, a saved script reused --- + +- id: global-codemode-reuses-saved-script + prompt: |- + how many open tasks does user 3 still have in our task tracker? + initial: ai_evals/fixtures/frontend/global/initial/open_tasks_script.json + runtime: + maxTurns: 8 + validate: + draftCountExactly: 0 + toolExpect: + # Running the deployed script or a preview of it both reuse its code. + requiredToolsAnyOf: + - - run_script + - test_run_script + forbiddenToolsUsed: + - write_script + - test_run_code + - deploy_workspace_item + assistantExpect: + # The tracker holds 13 open tasks for user 3: the count only a run can give. + requiredMentionsAnyOf: + - - "13" + # No draft for the judge to score: the deliverable is running the saved script rather than + # writing new code, checked on tool use above. + skipJudge: true + judgeChecklist: + - runs the existing open tasks script instead of writing new code + +- id: global-codemode-task-then-save + prompt: |- + Every Monday I need to know how many of the users at https://jsonplaceholder.typicode.com/users + live in each city. Get me this week's numbers, and keep whatever you used so I can rerun it + next week. Don't deploy anything yet. + initial: ai_evals/fixtures/frontend/global/initial/user_admin_empty.json + runtime: + maxTurns: 12 + validate: + draftCountExactly: 1 + requiredDrafts: + - type: script + valueIncludes: + - jsonplaceholder.typicode.com/users + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + judgeChecklist: + - the saved script fetches the users and counts them per city + - the script returns the per-city counts rather than the raw user list + - the script is kept as a draft and nothing is deployed + +# A one-off question: answered by running code, and nothing saved since the user did not ask to +# keep it. Users 4 and 6 tie at 14 open tasks, which only a run over the whole list gives. +- id: global-codemode-one-off-no-save + prompt: |- + Which user in our task tracker at https://jsonplaceholder.typicode.com/todos has the most + open tasks right now? + initial: ai_evals/fixtures/frontend/global/initial/user_admin_empty.json + runtime: + maxTurns: 8 + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - test_run_code + forbiddenToolsUsed: + - write_script + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - "14" + skipJudge: true + judgeChecklist: + - answers from a run of code over the tracker's tasks, saving nothing + +# Building an item stays authoring: the code-mode rule must not pull it into a bare run. +- id: global-codemode-authoring-not-code-mode + prompt: |- + Create a script at f/evals/global/open_tasks_per_user that returns how many open tasks each + user has in https://jsonplaceholder.typicode.com/todos. + initial: ai_evals/fixtures/frontend/global/initial/user_admin_empty.json + runtime: + maxTurns: 10 + validate: + draftCountExactly: 1 + requiredDrafts: + - type: script + path: f/evals/global/open_tasks_per_user + toolExpect: + requiredToolsUsed: + - write_script + forbiddenToolsUsed: + - test_run_code + - deploy_workspace_item + judgeChecklist: + - creates a script draft at f/evals/global/open_tasks_per_user + - the script fetches the todos and counts the open ones per user + - the script returns the per-user counts rather than the raw todo list diff --git a/ai_evals/core/previewFailureDetails.test.ts b/ai_evals/core/previewFailureDetails.test.ts new file mode 100644 index 0000000000..eac7eda7db --- /dev/null +++ b/ai_evals/core/previewFailureDetails.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from "bun:test"; +import { formatPreviewFailureDetails } from "./previewFailureDetails"; + +describe("formatPreviewFailureDetails", () => { + it("includes runtime logs and result excerpts for failed preview jobs", () => { + const details = formatPreviewFailureDetails({ + workspaceId: "ai-evals-crud-a1", + jobId: "job-123", + logs: "\nTypeError: Cannot read properties of undefined\n at listRecipes\n", + result: { error: "frontend called missing backend runnable" }, + }); + + expect(details).toContain("workspace=ai-evals-crud-a1"); + expect(details).toContain("job=job-123"); + expect(details).toContain("TypeError: Cannot read properties of undefined"); + expect(details).toContain("frontend called missing backend runnable"); + }); + + it("bounds noisy logs so check summaries stay readable", () => { + const details = formatPreviewFailureDetails({ + workspaceId: "workspace", + jobId: "job", + logs: "x".repeat(100), + maxCharacters: 20, + }); + + expect(details).toContain(`logs:\n…${"x".repeat(19)}`); + expect(details.length).toBeLessThan(80); + }); + + it("keeps the error at the end of a log after long install output", () => { + const installOutput = Array.from( + { length: 150 }, + (_, i) => `+ package-${i}@1.0.${i} installed from the registry`, + ).join("\n"); + const details = formatPreviewFailureDetails({ + workspaceId: "workspace", + jobId: "job", + logs: `${installOutput}\nerror: Cannot find module 'missing'\n at main (/tmp/main.ts:3:9)\n`, + result: { + error: { + name: "Error", + stack: "x".repeat(2000), + message: "Cannot find module", + }, + }, + }); + + expect(details).toContain( + "error: Cannot find module 'missing'\n at main (/tmp/main.ts:3:9)", + ); + expect(details).not.toContain("package-0@"); + expect(details).toContain("result:\nError: Cannot find module\nxxx"); + }); +}); diff --git a/ai_evals/core/previewFailureDetails.ts b/ai_evals/core/previewFailureDetails.ts new file mode 100644 index 0000000000..0817dd0d03 --- /dev/null +++ b/ai_evals/core/previewFailureDetails.ts @@ -0,0 +1,78 @@ +export interface PreviewFailureDetailsInput { + workspaceId: string; + jobId: string; + logs?: string | null; + result?: unknown; + maxCharacters?: number; +} + +export function formatPreviewFailureDetails( + input: PreviewFailureDetailsInput, +): string { + const parts = [`workspace=${input.workspaceId}; job=${input.jobId}`]; + const maxCharacters = input.maxCharacters ?? 1200; + // A job log starts with dependency install output and ends with what ran just + // before the failure: keep its tail. + const logExcerpt = normalizeExcerpt(input.logs, maxCharacters, "tail"); + const resultExcerpt = normalizeExcerpt( + formatResult(input.result), + maxCharacters, + "head", + ); + + if (logExcerpt) { + parts.push(`logs:\n${logExcerpt}`); + } + if (resultExcerpt) { + parts.push(`result:\n${resultExcerpt}`); + } + + return parts.join("\n"); +} + +function formatResult(result: unknown): string | null { + if (result == null) { + return null; + } + if (typeof result === "string") { + return result; + } + // A failed job's error serializes its message after the stack, which a long stack + // would push out of the excerpt. + const error = ( + result as { error?: { name?: unknown; message?: unknown; stack?: unknown } } + ).error; + if (error && typeof error === "object" && typeof error.message === "string") { + const name = typeof error.name === "string" ? `${error.name}: ` : ""; + const stack = typeof error.stack === "string" ? `\n${error.stack}` : ""; + return `${name}${error.message}${stack}`; + } + try { + return JSON.stringify(result); + } catch { + return String(result); + } +} + +function normalizeExcerpt( + value: string | null | undefined, + maxCharacters: number, + keep: "head" | "tail", +): string | null { + // Line breaks are kept: a traceback's frames and its ^^^ markers under the failing + // expression only read correctly line by line. + const normalized = value + ?.replace(/\r\n?/g, "\n") + .replace(/[ \t]+$/gm, "") + .replace(/\n{3,}/g, "\n\n") + .trim(); + if (!normalized) { + return null; + } + if (normalized.length <= maxCharacters) { + return normalized; + } + return keep === "tail" + ? `…${normalized.slice(normalized.length - (maxCharacters - 1))}` + : `${normalized.slice(0, maxCharacters - 1)}…`; +} diff --git a/ai_evals/core/types.ts b/ai_evals/core/types.ts index 2b667c3129..5e9fd0a362 100644 --- a/ai_evals/core/types.ts +++ b/ai_evals/core/types.ts @@ -311,6 +311,12 @@ export interface AssistantValidationSpec { * assistant say the right thing" expectations to the judge checklist. */ forbiddenMentions?: string[]; + /** + * `required`: the reply holds at least one ```wm-display block, and every one validates + * against the chat's display catalog (what the chat renders as a chart or table). + * `forbidden`: the reply holds none. + */ + displayBlocks?: "required" | "forbidden"; } export interface EvalCase { diff --git a/ai_evals/core/validators.test.ts b/ai_evals/core/validators.test.ts index 4668995a15..f0aa8f55a9 100644 --- a/ai_evals/core/validators.test.ts +++ b/ai_evals/core/validators.test.ts @@ -8,6 +8,7 @@ import { validateScriptState, validateAssistantExpectations, validateToolExpectations, + validateDisplayBlocks, } from "./validators"; describe("validateScriptState", () => { @@ -1373,3 +1374,19 @@ describe("validateCliWorkspace", () => { }); }); }); + +describe("validateDisplayBlocks", () => { + const fence = (value: unknown) => "```wm-display\n" + JSON.stringify(value) + "\n```"; + const chart = { chart: { type: "bar", data: [{ day: "Mon", n: 4 }], x: "day", y: "n" } }; + + it("requires every block to validate against the display catalog", () => { + const ok = validateDisplayBlocks(`Here:\n${fence(chart)}`, "required"); + expect(ok.every((c) => c.passed)).toBe(true); + const bad = validateDisplayBlocks( + `${fence(chart)}\n${fence({ chart: { ...chart.chart, y: "missing" } })}`, + "required" + ); + expect(bad.every((c) => c.passed)).toBe(false); + expect(validateDisplayBlocks("plain prose", "required").every((c) => c.passed)).toBe(false); + }); +}); diff --git a/ai_evals/core/validators.ts b/ai_evals/core/validators.ts index 6f596649df..0baf6f6f3a 100644 --- a/ai_evals/core/validators.ts +++ b/ai_evals/core/validators.ts @@ -1,5 +1,6 @@ import path from "node:path"; import ts from "typescript"; +import { parseFence } from "../../frontend/src/lib/components/display/displayCatalog"; import type { AppValidationSpec, AssistantValidationSpec, @@ -207,9 +208,38 @@ export function validateAssistantExpectations(input: { ); } + if (expect.displayBlocks) { + checks.push(...validateDisplayBlocks(text, expect.displayBlocks)); + } + return checks; } +const DISPLAY_BLOCK = /```wm-display[^\n]*\n([\s\S]*?)```/g; + +/** The ```wm-display blocks in `text`, checked with the parser the chat renders them with. */ +export function validateDisplayBlocks( + text: string, + mode: "required" | "forbidden" +): BenchmarkCheck[] { + const blocks = [...text.matchAll(DISPLAY_BLOCK)].map((m) => m[1]); + if (mode === "forbidden") { + return [check("reply holds no wm-display block", blocks.length === 0, truncateForDetails(text))]; + } + const failures = blocks + .map((source, i) => ({ i, parsed: parseFence(source) })) + .filter(({ parsed }) => !parsed.ok) + .map(({ i, parsed }) => `block ${i + 1}: ${parsed.ok ? "" : parsed.error}`); + return [ + check("reply holds a wm-display block", blocks.length > 0, truncateForDetails(text)), + check( + "every wm-display block validates against the display catalog", + blocks.length > 0 && failures.length === 0, + failures.join("\n") || undefined + ), + ]; +} + export function validateToolExpectations(input: { run: ModeRunOutput; toolExpect?: ToolValidationSpec; diff --git a/ai_evals/fixtures/frontend/global/initial/open_tasks_script.json b/ai_evals/fixtures/frontend/global/initial/open_tasks_script.json new file mode 100644 index 0000000000..60795eafb4 --- /dev/null +++ b/ai_evals/fixtures/frontend/global/initial/open_tasks_script.json @@ -0,0 +1,26 @@ +{ + "workspace": { + "scripts": [ + { + "path": "f/evals/global/open_tasks", + "summary": "Count a user's open tasks in the task tracker", + "description": "Reads the team's task tracker (https://jsonplaceholder.typicode.com/todos) and returns how many of the given user's tasks are still open, with their titles.", + "language": "bun", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "user_id": { + "type": "number", + "description": "The tracker's id for the user, e.g. 3" + } + }, + "required": [ + "user_id" + ] + }, + "content": "export async function main(user_id: number) {\n const todos: { title: string; completed: boolean }[] = await (\n await fetch(`https://jsonplaceholder.typicode.com/todos?userId=${user_id}`)\n ).json()\n const open = todos.filter((t) => !t.completed)\n return { user_id, open: open.length, titles: open.map((t) => t.title) }\n}\n" + } + ] + } +} diff --git a/ai_evals/modes/flow.ts b/ai_evals/modes/flow.ts index 1b3781c02d..dfdcb02783 100644 --- a/ai_evals/modes/flow.ts +++ b/ai_evals/modes/flow.ts @@ -4,6 +4,7 @@ import type { FrontendEvalModelConfig } from "../core/models"; import type { FlowValidationSpec } from "../core/types"; import { validateFlowState, type FlowState } from "../core/validators"; import type { BenchmarkArtifactFile, ModeRunner } from "../core/types"; +import { formatPreviewFailureDetails } from "../core/previewFailureDetails"; import { runFlowEval } from "../adapters/frontend/core/flow/flowEvalRunner"; import type { FlowWorkspaceFixtures } from "../adapters/frontend/core/flow/fileHelpers"; import { BackendPreviewClient } from "../adapters/frontend/backendPreview"; @@ -117,7 +118,12 @@ export function createFlowModeRunner( passed: completedJob.success, details: completedJob.success ? `workspace=${workspaceId}` - : `workspace=${workspaceId}; job=${completedJob.id}`, + : formatPreviewFailureDetails({ + workspaceId, + jobId: completedJob.id, + logs: completedJob.logs, + result: completedJob.result, + }), }, ], artifactFiles: [ diff --git a/ai_evals/modes/script.ts b/ai_evals/modes/script.ts index 0407caf208..a74ea8a541 100644 --- a/ai_evals/modes/script.ts +++ b/ai_evals/modes/script.ts @@ -3,6 +3,7 @@ import type { BackendValidationSettings } from "../core/backendValidation"; import type { FrontendEvalModelConfig } from "../core/models"; import { validateScriptState } from "../core/validators"; import type { BenchmarkArtifactFile, ModeRunner } from "../core/types"; +import { formatPreviewFailureDetails } from "../core/previewFailureDetails"; import { BackendPreviewClient } from "../adapters/frontend/backendPreview"; import { runScriptEval } from "../adapters/frontend/core/script/scriptEvalRunner"; import type { ScriptEvalState } from "../adapters/frontend/core/script/fileHelpers"; @@ -90,7 +91,12 @@ export function createScriptModeRunner( passed: completedJob.success, details: completedJob.success ? `workspace=${workspaceId}` - : `workspace=${workspaceId}; job=${completedJob.id}`, + : formatPreviewFailureDetails({ + workspaceId, + jobId: completedJob.id, + logs: completedJob.logs, + result: completedJob.result, + }), }, ], artifactFiles: [ diff --git a/backend/.sqlx/query-0177ee2ab01adcfe59cc879f1e7f8a8cfb42ad5ebc71e649b17ab39822a08f55.json b/backend/.sqlx/query-0177ee2ab01adcfe59cc879f1e7f8a8cfb42ad5ebc71e649b17ab39822a08f55.json new file mode 100644 index 0000000000..98ec62ccd2 --- /dev/null +++ b/backend/.sqlx/query-0177ee2ab01adcfe59cc879f1e7f8a8cfb42ad5ebc71e649b17ab39822a08f55.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id FROM resume_job WHERE job = $1 AND id <> ALL($2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Uuid", + "UuidArray" + ] + }, + "nullable": [ + false + ] + }, + "hash": "0177ee2ab01adcfe59cc879f1e7f8a8cfb42ad5ebc71e649b17ab39822a08f55" +} diff --git a/backend/.sqlx/query-02f554c24dc1f4c02972050b35ee187fa2216941aba03ca1862be8ca0201e14d.json b/backend/.sqlx/query-02f554c24dc1f4c02972050b35ee187fa2216941aba03ca1862be8ca0201e14d.json new file mode 100644 index 0000000000..a43556792f --- /dev/null +++ b/backend/.sqlx/query-02f554c24dc1f4c02972050b35ee187fa2216941aba03ca1862be8ca0201e14d.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO v2_job (id, workspace_id, kind) VALUES ($1, $2, 'flow')", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "02f554c24dc1f4c02972050b35ee187fa2216941aba03ca1862be8ca0201e14d" +} diff --git a/backend/.sqlx/query-07a601db659dcd09df5b6202ad1fdb66832fb9556a141e6c6dd401c8776612aa.json b/backend/.sqlx/query-07a601db659dcd09df5b6202ad1fdb66832fb9556a141e6c6dd401c8776612aa.json new file mode 100644 index 0000000000..2a9dfe432b --- /dev/null +++ b/backend/.sqlx/query-07a601db659dcd09df5b6202ad1fdb66832fb9556a141e6c6dd401c8776612aa.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT job_id, handed_jobs FROM ai_memory_turn\n WHERE workspace_id = $1 AND memory_id = $2 FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "job_id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "handed_jobs", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text", + "Uuid" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "07a601db659dcd09df5b6202ad1fdb66832fb9556a141e6c6dd401c8776612aa" +} diff --git a/backend/.sqlx/query-07b6a41db0a8714d9e2a060867a95d5ffc0f77af96d73f81a543b54234fa46e0.json b/backend/.sqlx/query-07b6a41db0a8714d9e2a060867a95d5ffc0f77af96d73f81a543b54234fa46e0.json new file mode 100644 index 0000000000..0c6a06082c --- /dev/null +++ b/backend/.sqlx/query-07b6a41db0a8714d9e2a060867a95d5ffc0f77af96d73f81a543b54234fa46e0.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO v2_job (id, workspace_id, kind, parent_job, root_job)\n VALUES ($1, $2, 'script', $3, $4)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Uuid", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "07b6a41db0a8714d9e2a060867a95d5ffc0f77af96d73f81a543b54234fa46e0" +} diff --git a/backend/.sqlx/query-0a2f6515f1900406d7356bcbdcdcc9d1b3922474df8cd1593efabcec327f80c2.json b/backend/.sqlx/query-0a2f6515f1900406d7356bcbdcdcc9d1b3922474df8cd1593efabcec327f80c2.json new file mode 100644 index 0000000000..377d7de087 --- /dev/null +++ b/backend/.sqlx/query-0a2f6515f1900406d7356bcbdcdcc9d1b3922474df8cd1593efabcec327f80c2.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_queue q SET suspend = 0\n FROM ai_agent_checkpoint c, v2_job j, v2_job_status s\n WHERE c.job_id = q.id AND j.id = q.id AND j.parent_job = $1 AND s.id = $1\n AND (s.flow_status->>'step')::int = jsonb_array_length(s.flow_status->'modules') - 1\n AND s.flow_status->'modules'->-1->>'job' = q.id::text\n AND q.suspend > 0 AND q.suspend_until IS NOT NULL\n RETURNING q.id, j.flow_step_id, c.checkpoint->'background' AS \"background\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "flow_step_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "background", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + true, + null + ] + }, + "hash": "0a2f6515f1900406d7356bcbdcdcc9d1b3922474df8cd1593efabcec327f80c2" +} diff --git a/backend/.sqlx/query-0abd057a9ebd0148c139542d7875dc86854fb2ea26177a2b7df75b651258ebbf.json b/backend/.sqlx/query-0abd057a9ebd0148c139542d7875dc86854fb2ea26177a2b7df75b651258ebbf.json new file mode 100644 index 0000000000..19fac0ed33 --- /dev/null +++ b/backend/.sqlx/query-0abd057a9ebd0148c139542d7875dc86854fb2ea26177a2b7df75b651258ebbf.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT suspend FROM v2_job_queue WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "suspend", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "0abd057a9ebd0148c139542d7875dc86854fb2ea26177a2b7df75b651258ebbf" +} diff --git a/backend/.sqlx/query-0b75b5efd2574e50a26d518b3f91d51f81536859c4aca5afd6c3a9d797bc45f2.json b/backend/.sqlx/query-0b75b5efd2574e50a26d518b3f91d51f81536859c4aca5afd6c3a9d797bc45f2.json new file mode 100644 index 0000000000..58364f1984 --- /dev/null +++ b/backend/.sqlx/query-0b75b5efd2574e50a26d518b3f91d51f81536859c4aca5afd6c3a9d797bc45f2.json @@ -0,0 +1,27 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO git_sync_pr_check_head (workspace_id, repo_resource_path, pr_number, head_sha)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (workspace_id, repo_resource_path, pr_number)\n DO UPDATE SET head_sha = EXCLUDED.head_sha, checked_at = now(), started = false\n WHERE $6\n OR ((git_sync_pr_check_head.head_sha <> EXCLUDED.head_sha\n OR (NOT git_sync_pr_check_head.started\n AND git_sync_pr_check_head.checked_at < now() - interval '10 minutes'))\n AND ($5::timestamptz IS NULL OR git_sync_pr_check_head.checked_at < $5))\n RETURNING 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Int8", + "Varchar", + "Timestamptz", + "Bool" + ] + }, + "nullable": [ + null + ] + }, + "hash": "0b75b5efd2574e50a26d518b3f91d51f81536859c4aca5afd6c3a9d797bc45f2" +} diff --git a/backend/.sqlx/query-0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002.json b/backend/.sqlx/query-0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002.json new file mode 100644 index 0000000000..040cd620cb --- /dev/null +++ b/backend/.sqlx/query-0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name, (extra_perms ->> $2)::boolean AS \"grant\",\n $2 = ANY(owners) AS \"target_owner!\", NULL::text AS blocked\n FROM folder WHERE workspace_id = $1 ORDER BY name", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "grant", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "target_owner!", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "blocked", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + null, + null, + null + ] + }, + "hash": "0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002" +} diff --git a/backend/.sqlx/query-0d2c4436a03bad0f21d28025354cb65810a931747d76f2ab40232ba378ee52bd.json b/backend/.sqlx/query-0d2c4436a03bad0f21d28025354cb65810a931747d76f2ab40232ba378ee52bd.json new file mode 100644 index 0000000000..3f45edeb05 --- /dev/null +++ b/backend/.sqlx/query-0d2c4436a03bad0f21d28025354cb65810a931747d76f2ab40232ba378ee52bd.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO autoscaling_recording (worker_group, until, started_by)\n VALUES ($1, now() + make_interval(secs => $2), $3)\n ON CONFLICT (worker_group) DO UPDATE SET until = EXCLUDED.until, started_by = EXCLUDED.started_by", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Float8", + "Text" + ] + }, + "nullable": [] + }, + "hash": "0d2c4436a03bad0f21d28025354cb65810a931747d76f2ab40232ba378ee52bd" +} diff --git a/backend/.sqlx/query-0e321f4b596c6bebd0a6d6beab7f01124e63ea722cc8bffa404820193c64b0bc.json b/backend/.sqlx/query-0e321f4b596c6bebd0a6d6beab7f01124e63ea722cc8bffa404820193c64b0bc.json new file mode 100644 index 0000000000..707669e898 --- /dev/null +++ b/backend/.sqlx/query-0e321f4b596c6bebd0a6d6beab7f01124e63ea722cc8bffa404820193c64b0bc.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO favorite (usr, workspace_id, path, favorite_kind)\n SELECT f.usr, $2::varchar, f.path, f.favorite_kind\n FROM favorite f\n WHERE f.workspace_id = $1\n AND (f.usr = $3 OR f.usr IN (SELECT username FROM usr WHERE workspace_id = $2))\n ON CONFLICT DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "0e321f4b596c6bebd0a6d6beab7f01124e63ea722cc8bffa404820193c64b0bc" +} diff --git a/backend/.sqlx/query-0e56511ecce592809473db715d265ba6ddcb764760bda384a52e156e28e1de3c.json b/backend/.sqlx/query-0e56511ecce592809473db715d265ba6ddcb764760bda384a52e156e28e1de3c.json new file mode 100644 index 0000000000..d30fd40b13 --- /dev/null +++ b/backend/.sqlx/query-0e56511ecce592809473db715d265ba6ddcb764760bda384a52e156e28e1de3c.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE git_sync_pr_check_head SET started = true\n WHERE workspace_id = $1 AND repo_resource_path = $2 AND pr_number = $3 AND head_sha = $4", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8", + "Text" + ] + }, + "nullable": [] + }, + "hash": "0e56511ecce592809473db715d265ba6ddcb764760bda384a52e156e28e1de3c" +} diff --git a/backend/.sqlx/query-0eb5d5f937797812ef9fd47011c8aebca6147fe4382b2edae418afaf4fa61674.json b/backend/.sqlx/query-0eb5d5f937797812ef9fd47011c8aebca6147fe4382b2edae418afaf4fa61674.json new file mode 100644 index 0000000000..af79886782 --- /dev/null +++ b/backend/.sqlx/query-0eb5d5f937797812ef9fd47011c8aebca6147fe4382b2edae418afaf4fa61674.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_status SET flow_status = jsonb_set(flow_status, '{test_subflows}', $2)\n WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Jsonb" + ] + }, + "nullable": [] + }, + "hash": "0eb5d5f937797812ef9fd47011c8aebca6147fe4382b2edae418afaf4fa61674" +} diff --git a/backend/.sqlx/query-0f0882ba9bb85a860144e42db442c45e0f4e22160db393477b066597d655bef0.json b/backend/.sqlx/query-0f0882ba9bb85a860144e42db442c45e0f4e22160db393477b066597d655bef0.json new file mode 100644 index 0000000000..66df22a40a --- /dev/null +++ b/backend/.sqlx/query-0f0882ba9bb85a860144e42db442c45e0f4e22160db393477b066597d655bef0.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, suspend, suspend_until)\n VALUES ($1, $2, now(), 1, now() + interval '1 hour')", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "0f0882ba9bb85a860144e42db442c45e0f4e22160db393477b066597d655bef0" +} diff --git a/backend/.sqlx/query-11142355eac844d0dc09d58991f20b61f5892b97ed3557230b43ce2a9ca65491.json b/backend/.sqlx/query-11142355eac844d0dc09d58991f20b61f5892b97ed3557230b43ce2a9ca65491.json new file mode 100644 index 0000000000..f8f90e1160 --- /dev/null +++ b/backend/.sqlx/query-11142355eac844d0dc09d58991f20b61f5892b97ed3557230b43ce2a9ca65491.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM ai_memory_turn t\n USING (SELECT workspace_id, memory_id, job_id FROM ai_memory_turn s\n WHERE NOT EXISTS (SELECT 1 FROM v2_job_queue q WHERE q.id = s.job_id)) stale\n WHERE t.workspace_id = stale.workspace_id AND t.memory_id = stale.memory_id\n AND t.job_id = stale.job_id\n RETURNING t.handed_jobs", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "handed_jobs", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + true + ] + }, + "hash": "11142355eac844d0dc09d58991f20b61f5892b97ed3557230b43ce2a9ca65491" +} diff --git a/backend/.sqlx/query-159f2030de3ba169925236c8c23720e820a132958cd64483cba8c8e40bf2a563.json b/backend/.sqlx/query-159f2030de3ba169925236c8c23720e820a132958cd64483cba8c8e40bf2a563.json new file mode 100644 index 0000000000..eee9af3784 --- /dev/null +++ b/backend/.sqlx/query-159f2030de3ba169925236c8c23720e820a132958cd64483cba8c8e40bf2a563.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE volume SET generation = generation + 1 - generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $3 AND lease_until > now()\n RETURNING name", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "159f2030de3ba169925236c8c23720e820a132958cd64483cba8c8e40bf2a563" +} diff --git a/backend/.sqlx/query-15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7.json b/backend/.sqlx/query-15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7.json new file mode 100644 index 0000000000..d442fa8e18 --- /dev/null +++ b/backend/.sqlx/query-15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7.json @@ -0,0 +1,37 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\",\n (extra_perms ->> $4)::boolean AS \"grant\"\n FROM folder WHERE workspace_id = $1 AND name = ANY($2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "via!", + "type_info": "TextArray" + }, + { + "ordinal": 2, + "name": "grant", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "TextArray", + "TextArray", + "Text" + ] + }, + "nullable": [ + false, + null, + null + ] + }, + "hash": "15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7" +} diff --git a/backend/.sqlx/query-1642ab69bebc6cde3760a4124fdb1192d9d25ebd688bf39806e92f8fe6e84529.json b/backend/.sqlx/query-1642ab69bebc6cde3760a4124fdb1192d9d25ebd688bf39806e92f8fe6e84529.json new file mode 100644 index 0000000000..aed565f5e9 --- /dev/null +++ b/backend/.sqlx/query-1642ab69bebc6cde3760a4124fdb1192d9d25ebd688bf39806e92f8fe6e84529.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT policy->>'execution_mode' = 'anonymous' FROM app\n WHERE path = $1 AND workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "1642ab69bebc6cde3760a4124fdb1192d9d25ebd688bf39806e92f8fe6e84529" +} diff --git a/backend/.sqlx/query-3955e57e216d169c30b1548a2252eb169329116cba57780fa90ecf2bdb910f34.json b/backend/.sqlx/query-19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66.json similarity index 70% rename from backend/.sqlx/query-3955e57e216d169c30b1548a2252eb169329116cba57780fa90ecf2bdb910f34.json rename to backend/.sqlx/query-19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66.json index 2fdb1ae80d..4521496742 100644 --- a/backend/.sqlx/query-3955e57e216d169c30b1548a2252eb169329116cba57780fa90ecf2bdb910f34.json +++ b/backend/.sqlx/query-19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), updated_by = $5, last_used_at = now(),\n lease_until = NULL, leased_by = NULL\n WHERE workspace_id = $1 AND name = $2", + "query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), updated_by = $5, last_used_at = now(),\n lease_until = NULL, leased_by = NULL, generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2", "describe": { "columns": [], "parameters": { @@ -14,5 +14,5 @@ }, "nullable": [] }, - "hash": "3955e57e216d169c30b1548a2252eb169329116cba57780fa90ecf2bdb910f34" + "hash": "19c481a0d6ecd4c0dfab6973e4732c2146953253ba6062ab05b34b6b35e41f66" } diff --git a/backend/.sqlx/query-1b8f8d4d6c2f825aaa22ae758852448bb1df27afa17b53faed97022c05608637.json b/backend/.sqlx/query-1b8f8d4d6c2f825aaa22ae758852448bb1df27afa17b53faed97022c05608637.json new file mode 100644 index 0000000000..458f341059 --- /dev/null +++ b/backend/.sqlx/query-1b8f8d4d6c2f825aaa22ae758852448bb1df27afa17b53faed97022c05608637.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT until, started_by FROM autoscaling_recording WHERE worker_group = $1 AND until > now()", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "until", + "type_info": "Timestamptz" + }, + { + "ordinal": 1, + "name": "started_by", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "1b8f8d4d6c2f825aaa22ae758852448bb1df27afa17b53faed97022c05608637" +} diff --git a/backend/.sqlx/query-1ed0bb86786f0601a06aedca7d343c2cd86a9902d92ed8953aed712ac1273534.json b/backend/.sqlx/query-1ed0bb86786f0601a06aedca7d343c2cd86a9902d92ed8953aed712ac1273534.json new file mode 100644 index 0000000000..a3cc5391ef --- /dev/null +++ b/backend/.sqlx/query-1ed0bb86786f0601a06aedca7d343c2cd86a9902d92ed8953aed712ac1273534.json @@ -0,0 +1,92 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT kind::text AS \"kind!\", runnable_id, runnable_path, raw_code, raw_lock,\n script_lang AS \"script_lang: ScriptLang\",\n COALESCE(args ? '_MODULES', false) AS \"has_modules!\"\n FROM v2_job WHERE id = $1 AND workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "kind!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "runnable_id", + "type_info": "Int8" + }, + { + "ordinal": 2, + "name": "runnable_path", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "raw_code", + "type_info": "Text" + }, + { + "ordinal": 4, + "name": "raw_lock", + "type_info": "Text" + }, + { + "ordinal": 5, + "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": 6, + "name": "has_modules!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text" + ] + }, + "nullable": [ + null, + true, + true, + true, + true, + true, + null + ] + }, + "hash": "1ed0bb86786f0601a06aedca7d343c2cd86a9902d92ed8953aed712ac1273534" +} diff --git a/backend/.sqlx/query-1ef7b9b0e6674bcd4f75ba25a05765f1013d5a13513f09b201e50786d0d4f4fe.json b/backend/.sqlx/query-1ef7b9b0e6674bcd4f75ba25a05765f1013d5a13513f09b201e50786d0d4f4fe.json new file mode 100644 index 0000000000..e33870d64f --- /dev/null +++ b/backend/.sqlx/query-1ef7b9b0e6674bcd4f75ba25a05765f1013d5a13513f09b201e50786d0d4f4fe.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT q.suspend, c.checkpoint->'handed_over' AS \"handed_over\", c.waiting_on\n FROM v2_job_queue q JOIN ai_agent_checkpoint c ON c.job_id = q.id WHERE q.id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "suspend", + "type_info": "Int4" + }, + { + "ordinal": 1, + "name": "handed_over", + "type_info": "Jsonb" + }, + { + "ordinal": 2, + "name": "waiting_on", + "type_info": "UuidArray" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + null, + false + ] + }, + "hash": "1ef7b9b0e6674bcd4f75ba25a05765f1013d5a13513f09b201e50786d0d4f4fe" +} diff --git a/backend/.sqlx/query-218134a776fd05e92f33bbe3277d0db5f6baf969b3f585e0ab0435b9d6893286.json b/backend/.sqlx/query-218134a776fd05e92f33bbe3277d0db5f6baf969b3f585e0ab0435b9d6893286.json new file mode 100644 index 0000000000..386e033f6b --- /dev/null +++ b/backend/.sqlx/query-218134a776fd05e92f33bbe3277d0db5f6baf969b3f585e0ab0435b9d6893286.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT DISTINCT j.runnable_path AS \"path!\" FROM v2_job_queue q\n JOIN v2_job j ON j.id = q.id\n WHERE q.workspace_id = $1\n AND j.kind IN ('dependencies', 'flowdependencies')\n AND j.runnable_path = ANY($2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path!", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "TextArray" + ] + }, + "nullable": [ + true + ] + }, + "hash": "218134a776fd05e92f33bbe3277d0db5f6baf969b3f585e0ab0435b9d6893286" +} diff --git a/backend/.sqlx/query-23f47f5207abe0cfaede197aeee485957990eb92fa3ce515895eab0d3f28bfdc.json b/backend/.sqlx/query-23f47f5207abe0cfaede197aeee485957990eb92fa3ce515895eab0d3f28bfdc.json deleted file mode 100644 index 8897e8a7de..0000000000 --- a/backend/.sqlx/query-23f47f5207abe0cfaede197aeee485957990eb92fa3ce515895eab0d3f28bfdc.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO volume (workspace_id, name, size_bytes, created_by, lease_until, leased_by)\n VALUES ($1, $2, 0, $3, now() + interval '60 seconds', $4)\n ON CONFLICT (workspace_id, name) DO UPDATE\n SET lease_until = now() + interval '60 seconds', leased_by = $4\n WHERE volume.lease_until IS NULL OR volume.lease_until < now()\n RETURNING name", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "name", - "type_info": "Varchar" - } - ], - "parameters": { - "Left": [ - "Varchar", - "Varchar", - "Varchar", - "Varchar" - ] - }, - "nullable": [ - false - ] - }, - "hash": "23f47f5207abe0cfaede197aeee485957990eb92fa3ce515895eab0d3f28bfdc" -} diff --git a/backend/.sqlx/query-e0ddd0ca6c3f94a26345d34a6b04c2e240bb90075bba33a91402655c9e764b30.json b/backend/.sqlx/query-284fe6b62e9a40a9daced00db0ed7aa86ca18e1415c736aae8fa6b55ac060913.json similarity index 60% rename from backend/.sqlx/query-e0ddd0ca6c3f94a26345d34a6b04c2e240bb90075bba33a91402655c9e764b30.json rename to backend/.sqlx/query-284fe6b62e9a40a9daced00db0ed7aa86ca18e1415c736aae8fa6b55ac060913.json index 283d501103..1bc52d69b1 100644 --- a/backend/.sqlx/query-e0ddd0ca6c3f94a26345d34a6b04c2e240bb90075bba33a91402655c9e764b30.json +++ b/backend/.sqlx/query-284fe6b62e9a40a9daced00db0ed7aa86ca18e1415c736aae8fa6b55ac060913.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT\n result AS \"result: sqlx::types::Json>\",\n result_columns,\n status = 'success' AS \"success!\",\n created_by AS \"created_by!\"\n FROM v2_job_completed c\n JOIN v2_job j USING (id)\n WHERE c.id = $1 AND c.workspace_id = $2 AND ($3::text[] IS NULL OR tag = ANY($3))", + "query": "SELECT\n result AS \"result: sqlx::types::Json>\",\n result_columns,\n status IN ('success', 'skipped') AS \"success!\",\n status = 'skipped' AS \"is_skipped!\",\n created_by AS \"created_by!\"\n FROM v2_job_completed c\n JOIN v2_job j USING (id)\n WHERE c.id = $1 AND c.workspace_id = $2 AND ($3::text[] IS NULL OR tag = ANY($3))", "describe": { "columns": [ { @@ -20,6 +20,11 @@ }, { "ordinal": 3, + "name": "is_skipped!", + "type_info": "Bool" + }, + { + "ordinal": 4, "name": "created_by!", "type_info": "Varchar" } @@ -35,8 +40,9 @@ true, true, null, + null, false ] }, - "hash": "e0ddd0ca6c3f94a26345d34a6b04c2e240bb90075bba33a91402655c9e764b30" + "hash": "284fe6b62e9a40a9daced00db0ed7aa86ca18e1415c736aae8fa6b55ac060913" } diff --git a/backend/.sqlx/query-28f188e6c6a58144f78beb0d518fca32f005e25eee1fb442cdcc5aa111ee05bb.json b/backend/.sqlx/query-28f188e6c6a58144f78beb0d518fca32f005e25eee1fb442cdcc5aa111ee05bb.json new file mode 100644 index 0000000000..c82d122a82 --- /dev/null +++ b/backend/.sqlx/query-28f188e6c6a58144f78beb0d518fca32f005e25eee1fb442cdcc5aa111ee05bb.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT job_id FROM ai_memory_turn WHERE workspace_id = $1 AND memory_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "job_id", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Text", + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "28f188e6c6a58144f78beb0d518fca32f005e25eee1fb442cdcc5aa111ee05bb" +} diff --git a/backend/.sqlx/query-2ae1bfc683bbefadf8777b06898fcf48ebbdff22e059a33bc9188f38460f964c.json b/backend/.sqlx/query-2ae1bfc683bbefadf8777b06898fcf48ebbdff22e059a33bc9188f38460f964c.json new file mode 100644 index 0000000000..77439bddcc --- /dev/null +++ b/backend/.sqlx/query-2ae1bfc683bbefadf8777b06898fcf48ebbdff22e059a33bc9188f38460f964c.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE volume SET generation = generation + 1 - generation % 2\n WHERE workspace_id = $1 AND name = $2 AND lease_until > now() AND leased_by = $3\n RETURNING name", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "2ae1bfc683bbefadf8777b06898fcf48ebbdff22e059a33bc9188f38460f964c" +} diff --git a/backend/.sqlx/query-2d67831f591efa5c37047f18a7dd8d33d862bba924ca098a1423e782df88fb1b.json b/backend/.sqlx/query-2d67831f591efa5c37047f18a7dd8d33d862bba924ca098a1423e782df88fb1b.json new file mode 100644 index 0000000000..7e06db789a --- /dev/null +++ b/backend/.sqlx/query-2d67831f591efa5c37047f18a7dd8d33d862bba924ca098a1423e782df88fb1b.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE volume SET generation = 2 WHERE workspace_id = 'test-workspace' AND name = 'test-vol'", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "2d67831f591efa5c37047f18a7dd8d33d862bba924ca098a1423e782df88fb1b" +} diff --git a/backend/.sqlx/query-2eb0de1f862785cc61aa5cc66641b2774bb0851593a55571ee9e7c2479c2919a.json b/backend/.sqlx/query-2eb0de1f862785cc61aa5cc66641b2774bb0851593a55571ee9e7c2479c2919a.json new file mode 100644 index 0000000000..4eaffc3551 --- /dev/null +++ b/backend/.sqlx/query-2eb0de1f862785cc61aa5cc66641b2774bb0851593a55571ee9e7c2479c2919a.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT extra_perms, created_by, generation, coalesce(lease_until > now(), false) AS \"write_live!\"\n FROM volume WHERE workspace_id = $1 AND name = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "extra_perms", + "type_info": "Jsonb" + }, + { + "ordinal": 1, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "generation", + "type_info": "Int8" + }, + { + "ordinal": 3, + "name": "write_live!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + null + ] + }, + "hash": "2eb0de1f862785cc61aa5cc66641b2774bb0851593a55571ee9e7c2479c2919a" +} diff --git a/backend/.sqlx/query-30be5ff70b3d7ee51a0f9b3ca3ec70bc018bb5ef051aafb7e20adf6e302846eb.json b/backend/.sqlx/query-30be5ff70b3d7ee51a0f9b3ca3ec70bc018bb5ef051aafb7e20adf6e302846eb.json new file mode 100644 index 0000000000..140504d89d --- /dev/null +++ b/backend/.sqlx/query-30be5ff70b3d7ee51a0f9b3ca3ec70bc018bb5ef051aafb7e20adf6e302846eb.json @@ -0,0 +1,25 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE ai_memory_turn t SET handed_jobs = t.handed_jobs - $4::text\n FROM (SELECT handed_jobs -> $4::text AS jobs FROM ai_memory_turn\n WHERE workspace_id = $1 AND memory_id = $2 AND job_id = $3) old\n WHERE t.workspace_id = $1 AND t.memory_id = $2 AND t.job_id = $3\n AND t.handed_jobs ? $4::text\n RETURNING old.jobs AS \"jobs: sqlx::types::Json>\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "jobs: sqlx::types::Json>", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text", + "Uuid", + "Uuid", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "30be5ff70b3d7ee51a0f9b3ca3ec70bc018bb5ef051aafb7e20adf6e302846eb" +} diff --git a/backend/.sqlx/query-33d6fc732dd52d31e2809a325eacb67b267c09bb4132fa2925cd70c15c9e208e.json b/backend/.sqlx/query-33d6fc732dd52d31e2809a325eacb67b267c09bb4132fa2925cd70c15c9e208e.json new file mode 100644 index 0000000000..7bbe47b5f9 --- /dev/null +++ b/backend/.sqlx/query-33d6fc732dd52d31e2809a325eacb67b267c09bb4132fa2925cd70c15c9e208e.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT value AS \"value: sqlx::types::Json\" FROM flow_version\n WHERE id = $1 AND workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value: sqlx::types::Json", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Int8", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "33d6fc732dd52d31e2809a325eacb67b267c09bb4132fa2925cd70c15c9e208e" +} diff --git a/backend/.sqlx/query-37c43f3271442e50ab3433daed339e337e2d3ee29f1420d32bfd370e585172ed.json b/backend/.sqlx/query-37c43f3271442e50ab3433daed339e337e2d3ee29f1420d32bfd370e585172ed.json new file mode 100644 index 0000000000..72b6b2fc92 --- /dev/null +++ b/backend/.sqlx/query-37c43f3271442e50ab3433daed339e337e2d3ee29f1420d32bfd370e585172ed.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT count(*) FROM v2_job WHERE workspace_id = 'test-workspace' AND trigger_kind = 'ci_test'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "37c43f3271442e50ab3433daed339e337e2d3ee29f1420d32bfd370e585172ed" +} diff --git a/backend/.sqlx/query-386144e570a7bbc7d2263f3104dd54107be058806ec5a45556b3304f791a6265.json b/backend/.sqlx/query-386144e570a7bbc7d2263f3104dd54107be058806ec5a45556b3304f791a6265.json new file mode 100644 index 0000000000..b87695b171 --- /dev/null +++ b/backend/.sqlx/query-386144e570a7bbc7d2263f3104dd54107be058806ec5a45556b3304f791a6265.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM ai_agent_checkpoint c\n JOIN v2_job_queue q ON q.id = c.job_id JOIN v2_job j ON j.id = c.job_id\n WHERE (j.parent_job = $1 OR j.root_job = $1)\n AND q.suspend > 0 AND q.suspend_until IS NOT NULL) AS \"parked!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "parked!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "386144e570a7bbc7d2263f3104dd54107be058806ec5a45556b3304f791a6265" +} diff --git a/backend/.sqlx/query-38755d1d28e0d6db5f9dd89f14cb7f6a74b1125069684aa22aafd9c7b4878714.json b/backend/.sqlx/query-38755d1d28e0d6db5f9dd89f14cb7f6a74b1125069684aa22aafd9c7b4878714.json new file mode 100644 index 0000000000..d64cb89142 --- /dev/null +++ b/backend/.sqlx/query-38755d1d28e0d6db5f9dd89f14cb7f6a74b1125069684aa22aafd9c7b4878714.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_status SET\n flow_status = jsonb_set(\n flow_status,\n array['modules', $2::int::TEXT, 'agent_actions_success'],\n COALESCE((\n SELECT jsonb_agg(e ORDER BY i)\n FROM jsonb_array_elements(\n flow_status->'modules'->$2::int->'agent_actions_success'\n ) WITH ORDINALITY AS t(e, i)\n WHERE i <= $3\n ), '[]'::jsonb) || CASE WHEN $4::bool IS NULL THEN '[]'::jsonb\n ELSE to_jsonb(ARRAY[$4::bool]) END\n )\n WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Int4", + "Int8", + "Bool" + ] + }, + "nullable": [] + }, + "hash": "38755d1d28e0d6db5f9dd89f14cb7f6a74b1125069684aa22aafd9c7b4878714" +} diff --git a/backend/.sqlx/query-12d69d85e25ffbed2dc37ef0faeb341b037aa66bc198f21fbc8de22e688f3d97.json b/backend/.sqlx/query-3c81ab38ce574091a292a931acce748869b6b5c4a761e07227c68765f6fba8c4.json similarity index 69% rename from backend/.sqlx/query-12d69d85e25ffbed2dc37ef0faeb341b037aa66bc198f21fbc8de22e688f3d97.json rename to backend/.sqlx/query-3c81ab38ce574091a292a931acce748869b6b5c4a761e07227c68765f6fba8c4.json index 223745919c..9c384ba391 100644 --- a/backend/.sqlx/query-12d69d85e25ffbed2dc37ef0faeb341b037aa66bc198f21fbc8de22e688f3d97.json +++ b/backend/.sqlx/query-3c81ab38ce574091a292a931acce748869b6b5c4a761e07227c68765f6fba8c4.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT\n result AS \"result: sqlx::types::Json>\",\n result_columns,\n status = 'success' AS \"success!\"\n FROM\n v2_job_completed\n WHERE\n id = $1 AND\n workspace_id = $2\n ", + "query": "\n SELECT\n result AS \"result: sqlx::types::Json>\",\n result_columns,\n status IN ('success', 'skipped') AS \"success!\"\n FROM\n v2_job_completed\n WHERE\n id = $1 AND\n workspace_id = $2\n ", "describe": { "columns": [ { @@ -31,5 +31,5 @@ null ] }, - "hash": "12d69d85e25ffbed2dc37ef0faeb341b037aa66bc198f21fbc8de22e688f3d97" + "hash": "3c81ab38ce574091a292a931acce748869b6b5c4a761e07227c68765f6fba8c4" } diff --git a/backend/.sqlx/query-3f54b049262014eb2c8098c21507d4dd6e5c084dbd5edb55c677f94cd5348027.json b/backend/.sqlx/query-3f54b049262014eb2c8098c21507d4dd6e5c084dbd5edb55c677f94cd5348027.json new file mode 100644 index 0000000000..211e971454 --- /dev/null +++ b/backend/.sqlx/query-3f54b049262014eb2c8098c21507d4dd6e5c084dbd5edb55c677f94cd5348027.json @@ -0,0 +1,59 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT recorded_at, worker_count, occupancy_rate_15s, occupancy_rate_5m, occupancy_rate_30m, jobs_waiting, decision\n FROM autoscaling_decision WHERE worker_group = $1 ORDER BY recorded_at DESC LIMIT $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "recorded_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 1, + "name": "worker_count", + "type_info": "Int4" + }, + { + "ordinal": 2, + "name": "occupancy_rate_15s", + "type_info": "Float4" + }, + { + "ordinal": 3, + "name": "occupancy_rate_5m", + "type_info": "Float4" + }, + { + "ordinal": 4, + "name": "occupancy_rate_30m", + "type_info": "Float4" + }, + { + "ordinal": 5, + "name": "jobs_waiting", + "type_info": "Jsonb" + }, + { + "ordinal": 6, + "name": "decision", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Int8" + ] + }, + "nullable": [ + false, + false, + true, + true, + true, + false, + false + ] + }, + "hash": "3f54b049262014eb2c8098c21507d4dd6e5c084dbd5edb55c677f94cd5348027" +} diff --git a/backend/.sqlx/query-423dc0716c7a6f63e311a069f67158960cd9df94fa0540f299fa31cd41a82c5a.json b/backend/.sqlx/query-423dc0716c7a6f63e311a069f67158960cd9df94fa0540f299fa31cd41a82c5a.json new file mode 100644 index 0000000000..d310922e0f --- /dev/null +++ b/backend/.sqlx/query-423dc0716c7a6f63e311a069f67158960cd9df94fa0540f299fa31cd41a82c5a.json @@ -0,0 +1,43 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT j.permissioned_as, v.extra_perms, v.created_by, v.generation\n FROM v2_job j\n JOIN v2_job_queue q ON q.id = j.id\n JOIN volume v ON v.workspace_id = j.workspace_id AND v.name = $3\n WHERE j.id = $1 AND j.workspace_id = $2 AND q.running AND q.worker = $4", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "permissioned_as", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "extra_perms", + "type_info": "Jsonb" + }, + { + "ordinal": 2, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "generation", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "423dc0716c7a6f63e311a069f67158960cd9df94fa0540f299fa31cd41a82c5a" +} diff --git a/backend/.sqlx/query-486197afc7a30e028c703f9cae6ed681766d18372ddb4db9d972ee7201acb262.json b/backend/.sqlx/query-486197afc7a30e028c703f9cae6ed681766d18372ddb4db9d972ee7201acb262.json new file mode 100644 index 0000000000..1b7f0c0878 --- /dev/null +++ b/backend/.sqlx/query-486197afc7a30e028c703f9cae6ed681766d18372ddb4db9d972ee7201acb262.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM ai_agent_checkpoint c\n JOIN v2_job_queue q ON q.id = c.job_id JOIN v2_job j ON j.id = c.job_id\n JOIN v2_job_status s ON s.id = $1\n WHERE j.parent_job = $1\n AND (s.flow_status->>'step')::int = jsonb_array_length(s.flow_status->'modules') - 1\n AND s.flow_status->'modules'->-1->>'job' = c.job_id::text\n AND q.suspend > 0 AND q.suspend_until IS NOT NULL) AS \"parked!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "parked!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "486197afc7a30e028c703f9cae6ed681766d18372ddb4db9d972ee7201acb262" +} diff --git a/backend/.sqlx/query-4c260718afc95b83abd83daca83361b028471ba1bfe2fc45a7dc2914f059c9c3.json b/backend/.sqlx/query-4c260718afc95b83abd83daca83361b028471ba1bfe2fc45a7dc2914f059c9c3.json new file mode 100644 index 0000000000..ddae680264 --- /dev/null +++ b/backend/.sqlx/query-4c260718afc95b83abd83daca83361b028471ba1bfe2fc45a7dc2914f059c9c3.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_status\n SET flow_status = JSONB_SET(\n flow_status,\n ARRAY['continued_on_error'],\n COALESCE(flow_status->'continued_on_error', '[]'::jsonb) || JSONB_BUILD_ARRAY($2::jsonb)\n )\n WHERE id = $1\n AND flow_status IS NOT NULL\n AND JSONB_ARRAY_LENGTH(COALESCE(flow_status->'continued_on_error', '[]'::jsonb)) < $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Jsonb", + "Int4" + ] + }, + "nullable": [] + }, + "hash": "4c260718afc95b83abd83daca83361b028471ba1bfe2fc45a7dc2914f059c9c3" +} diff --git a/backend/.sqlx/query-4c57ad6140469111d3f72e0a843da5b75c6f8e8974dfd36d2545fbdf1c454b1f.json b/backend/.sqlx/query-4c57ad6140469111d3f72e0a843da5b75c6f8e8974dfd36d2545fbdf1c454b1f.json new file mode 100644 index 0000000000..d805361f44 --- /dev/null +++ b/backend/.sqlx/query-4c57ad6140469111d3f72e0a843da5b75c6f8e8974dfd36d2545fbdf1c454b1f.json @@ -0,0 +1,80 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT content, lock, language AS \"language: ScriptLang\", path,\n COALESCE(modules IS NOT NULL AND modules <> '{}'::jsonb, false)\n AS \"has_modules!\"\n FROM script WHERE hash = $1 AND workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "content", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "lock", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "language: 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": 3, + "name": "path", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "has_modules!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Int8", + "Text" + ] + }, + "nullable": [ + false, + true, + false, + false, + null + ] + }, + "hash": "4c57ad6140469111d3f72e0a843da5b75c6f8e8974dfd36d2545fbdf1c454b1f" +} diff --git a/backend/.sqlx/query-4cc61e16a7f80dbc77462430b335ff08a9b4d2721f886995d9734f46b46d2f08.json b/backend/.sqlx/query-4cc61e16a7f80dbc77462430b335ff08a9b4d2721f886995d9734f46b46d2f08.json new file mode 100644 index 0000000000..b3eb5a13a3 --- /dev/null +++ b/backend/.sqlx/query-4cc61e16a7f80dbc77462430b335ff08a9b4d2721f886995d9734f46b46d2f08.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT r.value, a.url AS \"approved_url?\"\n FROM resource r\n LEFT JOIN github_app_repo_approval a\n ON a.workspace_id = r.workspace_id AND a.path = r.path\n WHERE r.workspace_id = $1 AND r.path = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value", + "type_info": "Jsonb" + }, + { + "ordinal": 1, + "name": "approved_url?", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + true, + false + ] + }, + "hash": "4cc61e16a7f80dbc77462430b335ff08a9b4d2721f886995d9734f46b46d2f08" +} diff --git a/backend/.sqlx/query-4ed6ff9056651bfb836c53af162855b6c8f60c2f899fe70d21359ae6b15df43f.json b/backend/.sqlx/query-4ed6ff9056651bfb836c53af162855b6c8f60c2f899fe70d21359ae6b15df43f.json new file mode 100644 index 0000000000..bebb8f5c53 --- /dev/null +++ b/backend/.sqlx/query-4ed6ff9056651bfb836c53af162855b6c8f60c2f899fe70d21359ae6b15df43f.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO ai_agent_checkpoint (job_id, workspace_id, checkpoint, waiting_on)\n VALUES ($1, $2, $3, $4)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Jsonb", + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "4ed6ff9056651bfb836c53af162855b6c8f60c2f899fe70d21359ae6b15df43f" +} diff --git a/backend/.sqlx/query-5355271bf33a45184745d3f06c064b4bdd2ef4727b664f0fb9044eaa46a454db.json b/backend/.sqlx/query-5355271bf33a45184745d3f06c064b4bdd2ef4727b664f0fb9044eaa46a454db.json new file mode 100644 index 0000000000..4728a15cd6 --- /dev/null +++ b/backend/.sqlx/query-5355271bf33a45184745d3f06c064b4bdd2ef4727b664f0fb9044eaa46a454db.json @@ -0,0 +1,46 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT\n f.args as \"args: Json>>\",\n fs.flow_status as \"step_flow_status: Json\",\n rs.flow_status as \"run_status: Json\",\n r.runnable_path,\n r.id as root_job_id\n FROM v2_job f\n LEFT JOIN v2_job_status fs ON fs.id = f.id\n INNER JOIN v2_job r\n ON r.id = COALESCE(f.root_job, f.flow_innermost_root_job, f.parent_job, f.id)\n LEFT JOIN v2_job_status rs ON rs.id = r.id\n WHERE f.id = $1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "args: Json>>", + "type_info": "Jsonb" + }, + { + "ordinal": 1, + "name": "step_flow_status: Json", + "type_info": "Jsonb" + }, + { + "ordinal": 2, + "name": "run_status: Json", + "type_info": "Jsonb" + }, + { + "ordinal": 3, + "name": "runnable_path", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "root_job_id", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + true, + true, + true, + true, + false + ] + }, + "hash": "5355271bf33a45184745d3f06c064b4bdd2ef4727b664f0fb9044eaa46a454db" +} diff --git a/backend/.sqlx/query-14004a7c1641a3157eddd571fea11a1dfb1422187200119268b2342b47a960c6.json b/backend/.sqlx/query-54549a1aca624587a1f91c00f54fdcc887172d6a4c2081af6f2fafe249c5c29a.json similarity index 68% rename from backend/.sqlx/query-14004a7c1641a3157eddd571fea11a1dfb1422187200119268b2342b47a960c6.json rename to backend/.sqlx/query-54549a1aca624587a1f91c00f54fdcc887172d6a4c2081af6f2fafe249c5c29a.json index 9a6ae60a49..081f9be2fa 100644 --- a/backend/.sqlx/query-14004a7c1641a3157eddd571fea11a1dfb1422187200119268b2342b47a960c6.json +++ b/backend/.sqlx/query-54549a1aca624587a1f91c00f54fdcc887172d6a4c2081af6f2fafe249c5c29a.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO volume (workspace_id, name, size_bytes, created_by, lease_until, leased_by)\n VALUES ($1, $2, 0, $3, now() + interval '60 seconds', $4)\n ON CONFLICT (workspace_id, name) DO UPDATE\n SET lease_until = now() + interval '60 seconds', leased_by = $4\n WHERE volume.lease_until IS NULL OR volume.lease_until < now()\n RETURNING name", + "query": "INSERT INTO volume (workspace_id, name, size_bytes, created_by, lease_until, leased_by)\n VALUES ($1, $2, 0, $3, now() + interval '60 seconds', $4)\n ON CONFLICT (workspace_id, name) DO UPDATE\n SET lease_until = now() + interval '60 seconds', leased_by = $4,\n generation = volume.generation + volume.generation % 2\n WHERE volume.lease_until IS NULL OR volume.lease_until < now()\n RETURNING name", "describe": { "columns": [ { @@ -21,5 +21,5 @@ false ] }, - "hash": "14004a7c1641a3157eddd571fea11a1dfb1422187200119268b2342b47a960c6" + "hash": "54549a1aca624587a1f91c00f54fdcc887172d6a4c2081af6f2fafe249c5c29a" } diff --git a/backend/.sqlx/query-566a8179a5f0d0d1a22aad7fee51156ea200f06b15c16856f61f0a13bea1fa34.json b/backend/.sqlx/query-566a8179a5f0d0d1a22aad7fee51156ea200f06b15c16856f61f0a13bea1fa34.json new file mode 100644 index 0000000000..2d4821636b --- /dev/null +++ b/backend/.sqlx/query-566a8179a5f0d0d1a22aad7fee51156ea200f06b15c16856f61f0a13bea1fa34.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM git_sync_pr_check_head\n WHERE workspace_id = $1 AND repo_resource_path = $2 AND pr_number <> ALL($3)\n AND checked_at < $4", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8Array", + "Timestamptz" + ] + }, + "nullable": [] + }, + "hash": "566a8179a5f0d0d1a22aad7fee51156ea200f06b15c16856f61f0a13bea1fa34" +} diff --git a/backend/.sqlx/query-583cd9ab417a5d11399f77865cf05e089418401f72666c2cde20fee96963fabe.json b/backend/.sqlx/query-583cd9ab417a5d11399f77865cf05e089418401f72666c2cde20fee96963fabe.json new file mode 100644 index 0000000000..81f6f1fab7 --- /dev/null +++ b/backend/.sqlx/query-583cd9ab417a5d11399f77865cf05e089418401f72666c2cde20fee96963fabe.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT DISTINCT path FROM script WHERE workspace_id = $1 AND path = ANY($2) AND created_at > now() - make_interval(secs => $3)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "TextArray", + "Float8" + ] + }, + "nullable": [ + false + ] + }, + "hash": "583cd9ab417a5d11399f77865cf05e089418401f72666c2cde20fee96963fabe" +} diff --git a/backend/.sqlx/query-58a1ac3bd426accc18536cdb400dbf8e6fe2d383bf45037fea79a2c6664178b2.json b/backend/.sqlx/query-58a1ac3bd426accc18536cdb400dbf8e6fe2d383bf45037fea79a2c6664178b2.json new file mode 100644 index 0000000000..ec000054d4 --- /dev/null +++ b/backend/.sqlx/query-58a1ac3bd426accc18536cdb400dbf8e6fe2d383bf45037fea79a2c6664178b2.json @@ -0,0 +1,65 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT typ AS \"typ: UserDraftItemKind\", path FROM draft\n WHERE workspace_id = $1 AND email = $2\n AND (typ::text, path) IN (SELECT * FROM unnest($3::text[], $4::text[]))\n FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "typ: UserDraftItemKind", + "type_info": { + "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" + ] + } + } + } + }, + { + "ordinal": 1, + "name": "path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "TextArray", + "TextArray" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "58a1ac3bd426accc18536cdb400dbf8e6fe2d383bf45037fea79a2c6664178b2" +} diff --git a/backend/.sqlx/query-58ae943b41b2783c39597014654ca77562045bbef4dcd771820e744dea9c6b78.json b/backend/.sqlx/query-58ae943b41b2783c39597014654ca77562045bbef4dcd771820e744dea9c6b78.json new file mode 100644 index 0000000000..2343c74f5c --- /dev/null +++ b/backend/.sqlx/query-58ae943b41b2783c39597014654ca77562045bbef4dcd771820e744dea9c6b78.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE ai_memory_turn SET job_id = $3, handed_jobs = $4\n WHERE workspace_id = $1 AND memory_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Uuid", + "Uuid", + "Jsonb" + ] + }, + "nullable": [] + }, + "hash": "58ae943b41b2783c39597014654ca77562045bbef4dcd771820e744dea9c6b78" +} diff --git a/backend/.sqlx/query-6204479b0fdb9492aaa4fed3bb128153cb03925398c43ce5c2dbe111399a34c4.json b/backend/.sqlx/query-6204479b0fdb9492aaa4fed3bb128153cb03925398c43ce5c2dbe111399a34c4.json new file mode 100644 index 0000000000..72c379be9a --- /dev/null +++ b/backend/.sqlx/query-6204479b0fdb9492aaa4fed3bb128153cb03925398c43ce5c2dbe111399a34c4.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id, value AS \"value: sqlx::types::Json\", approver, approved\n FROM resume_job WHERE job = $1 AND id <> ALL($2) ORDER BY created_at ASC", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "value: sqlx::types::Json", + "type_info": "Jsonb" + }, + { + "ordinal": 2, + "name": "approver", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "approved", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid", + "UuidArray" + ] + }, + "nullable": [ + false, + false, + true, + false + ] + }, + "hash": "6204479b0fdb9492aaa4fed3bb128153cb03925398c43ce5c2dbe111399a34c4" +} diff --git a/backend/.sqlx/query-65148bf40198716608e6b78e51ea606f1a13a5c1889537800710f72619cfb323.json b/backend/.sqlx/query-65148bf40198716608e6b78e51ea606f1a13a5c1889537800710f72619cfb323.json new file mode 100644 index 0000000000..dbe79b912f --- /dev/null +++ b/backend/.sqlx/query-65148bf40198716608e6b78e51ea606f1a13a5c1889537800710f72619cfb323.json @@ -0,0 +1,25 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT DISTINCT d.path FROM draft d,\n jsonb_array_elements(CASE WHEN jsonb_typeof(d.value::jsonb->'drafts') = 'array'\n THEN d.value::jsonb->'drafts' ELSE '[]' END) node\n WHERE d.workspace_id = $1 AND d.email = $2 AND d.typ = 'data_pipeline'\n AND d.path = ANY($3::text[])\n AND CASE WHEN (node->1->'script'->>'hash' ~ '^[0-9a-f]{16}$') IS NOT TRUE THEN false\n ELSE NOT EXISTS (SELECT 1 FROM script sc WHERE sc.workspace_id = $4::text\n AND sc.hash = ('x' || (node->1->'script'->>'hash'))::bit(64)::bigint)\n END\n ORDER BY d.path", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "TextArray", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "65148bf40198716608e6b78e51ea606f1a13a5c1889537800710f72619cfb323" +} diff --git a/backend/.sqlx/query-6af668cd83504e0fe701647047295c32938dcc2b3484e6d2951fb6520e76ebc6.json b/backend/.sqlx/query-6af668cd83504e0fe701647047295c32938dcc2b3484e6d2951fb6520e76ebc6.json new file mode 100644 index 0000000000..39c047071d --- /dev/null +++ b/backend/.sqlx/query-6af668cd83504e0fe701647047295c32938dcc2b3484e6d2951fb6520e76ebc6.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT DISTINCT imported_path FROM dependency_map WHERE workspace_id = $1 AND importer_path = $2 AND importer_kind = 'script'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "imported_path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "6af668cd83504e0fe701647047295c32938dcc2b3484e6d2951fb6520e76ebc6" +} diff --git a/backend/.sqlx/query-6b3f5fc6d31dd4557a4ac7595ccf22f5ebe6c7568c0afaf2bd5d1a13717d518b.json b/backend/.sqlx/query-6b3f5fc6d31dd4557a4ac7595ccf22f5ebe6c7568c0afaf2bd5d1a13717d518b.json new file mode 100644 index 0000000000..42923e6deb --- /dev/null +++ b/backend/.sqlx/query-6b3f5fc6d31dd4557a4ac7595ccf22f5ebe6c7568c0afaf2bd5d1a13717d518b.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM usr WHERE workspace_id = $1 AND email = $2 AND disabled = false)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "6b3f5fc6d31dd4557a4ac7595ccf22f5ebe6c7568c0afaf2bd5d1a13717d518b" +} diff --git a/backend/.sqlx/query-7074277ce924e9a1312a430d958d16395c83dfa58164b432e3a41bb9063fc9fa.json b/backend/.sqlx/query-7074277ce924e9a1312a430d958d16395c83dfa58164b432e3a41bb9063fc9fa.json new file mode 100644 index 0000000000..aa8c3d3329 --- /dev/null +++ b/backend/.sqlx/query-7074277ce924e9a1312a430d958d16395c83dfa58164b432e3a41bb9063fc9fa.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM github_app_repo_approval WHERE workspace_id = $1 AND path = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "7074277ce924e9a1312a430d958d16395c83dfa58164b432e3a41bb9063fc9fa" +} diff --git a/backend/.sqlx/query-7154435ce9913ddf408033251e9b5f582b058750ec7cf2fee30dfa30f554d732.json b/backend/.sqlx/query-7154435ce9913ddf408033251e9b5f582b058750ec7cf2fee30dfa30f554d732.json new file mode 100644 index 0000000000..268d94c255 --- /dev/null +++ b/backend/.sqlx/query-7154435ce9913ddf408033251e9b5f582b058750ec7cf2fee30dfa30f554d732.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM autoscaling_recording WHERE worker_group = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "7154435ce9913ddf408033251e9b5f582b058750ec7cf2fee30dfa30f554d732" +} diff --git a/backend/.sqlx/query-71b94ff615d2c5bf4f5d2ec8d02dd96732c9960c0bd654b4fd1d6322e5ba3343.json b/backend/.sqlx/query-71b94ff615d2c5bf4f5d2ec8d02dd96732c9960c0bd654b4fd1d6322e5ba3343.json new file mode 100644 index 0000000000..f059560d80 --- /dev/null +++ b/backend/.sqlx/query-71b94ff615d2c5bf4f5d2ec8d02dd96732c9960c0bd654b4fd1d6322e5ba3343.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT checkpoint AS \"checkpoint: sqlx::types::Json>\"\n FROM ai_agent_checkpoint WHERE job_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "checkpoint: sqlx::types::Json>", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "71b94ff615d2c5bf4f5d2ec8d02dd96732c9960c0bd654b4fd1d6322e5ba3343" +} diff --git a/backend/.sqlx/query-7577b7caaeb39fa85236d941bbe225b0815d894127883ef8ea81e052dd110cdb.json b/backend/.sqlx/query-7577b7caaeb39fa85236d941bbe225b0815d894127883ef8ea81e052dd110cdb.json new file mode 100644 index 0000000000..2174152c6a --- /dev/null +++ b/backend/.sqlx/query-7577b7caaeb39fa85236d941bbe225b0815d894127883ef8ea81e052dd110cdb.json @@ -0,0 +1,66 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO draft (workspace_id, path, typ, value, created_at, email, base)\n SELECT $2::text, path, typ,\n to_json(\n CASE WHEN typ IN ('script', 'flow') THEN clean - 'on_behalf_of' ELSE clean END\n - CASE WHEN typ = 'flow' THEN 'version_id'\n WHEN typ IN ('app', 'raw_app') THEN 'parent_version'\n ELSE '' END\n - CASE WHEN typ <> 'script' THEN ''\n WHEN (clean->>'parent_hash' ~ '^[0-9a-f]{16}$') IS NOT TRUE THEN 'parent_hash'\n WHEN EXISTS (SELECT 1 FROM script sc WHERE sc.workspace_id = $2::text\n AND sc.hash = ('x' || (clean->>'parent_hash'))::bit(64)::bigint)\n THEN '' ELSE 'parent_hash' END\n ),\n created_at, email,\n CASE WHEN typ = 'script' AND base ~ '^[0-9a-f]{16}$' THEN\n CASE WHEN EXISTS (SELECT 1 FROM script sc WHERE sc.workspace_id = $2::text\n AND sc.hash = ('x' || base)::bit(64)::bigint)\n THEN base END\n END\n FROM (\n SELECT d.path, d.typ, d.created_at, d.email, d.base,\n replace(replace(replace(d.value::text, chr(92) || chr(92), chr(1)), chr(92) || 'u0000', ''), chr(1), chr(92) || chr(92))::jsonb AS clean\n FROM draft d\n WHERE d.workspace_id = $1\n AND CASE WHEN $4::text[] IS NULL THEN d.email = $3 OR d.email IS NULL\n ELSE d.email = $3\n AND (d.typ::text, d.path) IN (SELECT * FROM unnest($4::text[], $5::text[]))\n END\n ) s\n ON CONFLICT DO NOTHING\n RETURNING typ AS \"typ: UserDraftItemKind\", path", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "typ: UserDraftItemKind", + "type_info": { + "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" + ] + } + } + } + }, + { + "ordinal": 1, + "name": "path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Text", + "TextArray", + "TextArray" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "7577b7caaeb39fa85236d941bbe225b0815d894127883ef8ea81e052dd110cdb" +} diff --git a/backend/.sqlx/query-76f0d44dc51f391d7563c2a5a1ff674a0d953d4a4709ab21f6651f0438c351d5.json b/backend/.sqlx/query-76f0d44dc51f391d7563c2a5a1ff674a0d953d4a4709ab21f6651f0438c351d5.json new file mode 100644 index 0000000000..a7f17ad18a --- /dev/null +++ b/backend/.sqlx/query-76f0d44dc51f391d7563c2a5a1ff674a0d953d4a4709ab21f6651f0438c351d5.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_status SET\n flow_status = jsonb_set(\n flow_status,\n array['modules', $2::int::TEXT, 'agent_actions_success'],\n (\n SELECT jsonb_agg(CASE WHEN i = $3 THEN to_jsonb($4::bool) ELSE arr->i END ORDER BY i)\n FROM (SELECT COALESCE(\n flow_status->'modules'->$2::int->'agent_actions_success', '[]'::jsonb\n ) AS arr) a,\n generate_series(0, GREATEST(jsonb_array_length(arr) - 1, $3)) AS i\n )\n )\n WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Int4", + "Int4", + "Bool" + ] + }, + "nullable": [] + }, + "hash": "76f0d44dc51f391d7563c2a5a1ff674a0d953d4a4709ab21f6651f0438c351d5" +} diff --git a/backend/.sqlx/query-770dc2693c52a4112f613a148842024e7579dd22173b865fc07761eb73e2d534.json b/backend/.sqlx/query-770dc2693c52a4112f613a148842024e7579dd22173b865fc07761eb73e2d534.json new file mode 100644 index 0000000000..5343df8b52 --- /dev/null +++ b/backend/.sqlx/query-770dc2693c52a4112f613a148842024e7579dd22173b865fc07761eb73e2d534.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO autoscaling_decision\n (worker_group, worker_count, occupancy_rate_15s, occupancy_rate_5m, occupancy_rate_30m, jobs_waiting, decision)\n VALUES ($1, $2, $3, $4, $5, $6, $7)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Int4", + "Float4", + "Float4", + "Float4", + "Jsonb", + "Text" + ] + }, + "nullable": [] + }, + "hash": "770dc2693c52a4112f613a148842024e7579dd22173b865fc07761eb73e2d534" +} diff --git a/backend/.sqlx/query-4e14b95c57c6f987f020376f76ad4dd0ff0d043b3eff62863c8f8db89ad34a4e.json b/backend/.sqlx/query-789efb0a5e94c0f2c8943b82b08024b90907b624e420e3d67afc1296fbb35d5c.json similarity index 67% rename from backend/.sqlx/query-4e14b95c57c6f987f020376f76ad4dd0ff0d043b3eff62863c8f8db89ad34a4e.json rename to backend/.sqlx/query-789efb0a5e94c0f2c8943b82b08024b90907b624e420e3d67afc1296fbb35d5c.json index 1e83c28a49..0ad01b03c4 100644 --- a/backend/.sqlx/query-4e14b95c57c6f987f020376f76ad4dd0ff0d043b3eff62863c8f8db89ad34a4e.json +++ b/backend/.sqlx/query-789efb0a5e94c0f2c8943b82b08024b90907b624e420e3d67afc1296fbb35d5c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT result AS \"result: sqlx::types::Json\",\n status = 'success' AS \"success!\"\n FROM v2_job_completed WHERE id = $1 AND workspace_id = $2", + "query": "SELECT result AS \"result: sqlx::types::Json\",\n status IN ('success', 'skipped') AS \"success!\"\n FROM v2_job_completed WHERE id = $1 AND workspace_id = $2", "describe": { "columns": [ { @@ -25,5 +25,5 @@ null ] }, - "hash": "4e14b95c57c6f987f020376f76ad4dd0ff0d043b3eff62863c8f8db89ad34a4e" + "hash": "789efb0a5e94c0f2c8943b82b08024b90907b624e420e3d67afc1296fbb35d5c" } diff --git a/backend/.sqlx/query-7a14147a9d8d566e6ea627f32f63a6ac6f928103dd7725060712fa306ea0ccf1.json b/backend/.sqlx/query-7a14147a9d8d566e6ea627f32f63a6ac6f928103dd7725060712fa306ea0ccf1.json new file mode 100644 index 0000000000..b6b76b39bc --- /dev/null +++ b/backend/.sqlx/query-7a14147a9d8d566e6ea627f32f63a6ac6f928103dd7725060712fa306ea0ccf1.json @@ -0,0 +1,42 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH holding AS (\n -- Holding a worker, by the same test the fairness refresh counts with: a\n -- live runtime ping, and not a flow job, which stays running between steps\n -- without a worker.\n SELECT DISTINCT q.workspace_id FROM v2_job_queue q\n JOIN v2_job j ON j.id = q.id\n JOIN v2_job_runtime r ON r.id = q.id\n WHERE q.tag = $1 AND q.running = true AND q.suspend_until IS NULL\n AND q.workspace_id = ANY($3::text[])\n AND r.ping > NOW() - interval '60 seconds'\n AND j.kind NOT IN ('flow', 'flowpreview', 'flownode', 'singlestepflow')\n ), waiting AS (\n SELECT q.workspace_id, q.scheduled_for, h.workspace_id IS NOT NULL AS excluded\n FROM v2_job_queue q LEFT JOIN holding h USING (workspace_id)\n WHERE q.tag = $1\n AND q.scheduled_for <= NOW() - $2::interval\n AND q.running = false\n )\n SELECT COUNT(*) FILTER (WHERE NOT excluded) as count,\n COUNT(*) FILTER (WHERE excluded) as excluded_count,\n MIN(scheduled_for) FILTER (WHERE NOT excluded) as oldest_job,\n array_agg(DISTINCT workspace_id) FILTER (WHERE excluded) as excluded_workspaces\n FROM waiting\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count", + "type_info": "Int8" + }, + { + "ordinal": 1, + "name": "excluded_count", + "type_info": "Int8" + }, + { + "ordinal": 2, + "name": "oldest_job", + "type_info": "Timestamptz" + }, + { + "ordinal": 3, + "name": "excluded_workspaces", + "type_info": "VarcharArray" + } + ], + "parameters": { + "Left": [ + "Text", + "Interval", + "TextArray" + ] + }, + "nullable": [ + null, + null, + null, + null + ] + }, + "hash": "7a14147a9d8d566e6ea627f32f63a6ac6f928103dd7725060712fa306ea0ccf1" +} diff --git a/backend/.sqlx/query-7ebd9e0aa07232e3d1c76a21f7a9425a26f76bc83461065cf02b150cb86d28de.json b/backend/.sqlx/query-7ebd9e0aa07232e3d1c76a21f7a9425a26f76bc83461065cf02b150cb86d28de.json new file mode 100644 index 0000000000..c9cb261c62 --- /dev/null +++ b/backend/.sqlx/query-7ebd9e0aa07232e3d1c76a21f7a9425a26f76bc83461065cf02b150cb86d28de.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM ai_agent_checkpoint c\n JOIN v2_job_queue q ON q.id = c.job_id JOIN v2_job j ON j.id = c.job_id\n WHERE (j.parent_job = $1 OR j.root_job = $1)\n AND q.suspend > 0 AND q.suspend_until IS NOT NULL) AS \"parked!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "parked!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "7ebd9e0aa07232e3d1c76a21f7a9425a26f76bc83461065cf02b150cb86d28de" +} diff --git a/backend/.sqlx/query-8338b741d782c6c4273b1c98c7e62763959428e37f83ff376cd9018d11ea21ed.json b/backend/.sqlx/query-8338b741d782c6c4273b1c98c7e62763959428e37f83ff376cd9018d11ea21ed.json new file mode 100644 index 0000000000..2408ee318c --- /dev/null +++ b/backend/.sqlx/query-8338b741d782c6c4273b1c98c7e62763959428e37f83ff376cd9018d11ea21ed.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT leased_by, generation FROM volume WHERE workspace_id = 'test-workspace' AND name = 'test-vol'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "leased_by", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "generation", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + true, + false + ] + }, + "hash": "8338b741d782c6c4273b1c98c7e62763959428e37f83ff376cd9018d11ea21ed" +} diff --git a/backend/.sqlx/query-85a9967ab419bd1f09a2be7751ff8d15cb8431bf05fb34a7b99d03a2a86e48ca.json b/backend/.sqlx/query-85a9967ab419bd1f09a2be7751ff8d15cb8431bf05fb34a7b99d03a2a86e48ca.json new file mode 100644 index 0000000000..73d045ea54 --- /dev/null +++ b/backend/.sqlx/query-85a9967ab419bd1f09a2be7751ff8d15cb8431bf05fb34a7b99d03a2a86e48ca.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET large_file_storage = $1 WHERE workspace_id = 'test-workspace'", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Jsonb" + ] + }, + "nullable": [] + }, + "hash": "85a9967ab419bd1f09a2be7751ff8d15cb8431bf05fb34a7b99d03a2a86e48ca" +} diff --git a/backend/.sqlx/query-7ce06d4f623932fce12352be3a09ba8973a2ef1defa36c6d46d9c1c6406a7c33.json b/backend/.sqlx/query-85ac712e057207d1db48303925b2ca08479830f6de789cbc64661509fccba9ce.json similarity index 56% rename from backend/.sqlx/query-7ce06d4f623932fce12352be3a09ba8973a2ef1defa36c6d46d9c1c6406a7c33.json rename to backend/.sqlx/query-85ac712e057207d1db48303925b2ca08479830f6de789cbc64661509fccba9ce.json index 8cbe7146b6..8a8c1c6f2e 100644 --- a/backend/.sqlx/query-7ce06d4f623932fce12352be3a09ba8973a2ef1defa36c6d46d9c1c6406a7c33.json +++ b/backend/.sqlx/query-85ac712e057207d1db48303925b2ca08479830f6de789cbc64661509fccba9ce.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE volume SET lease_until = NULL, leased_by = NULL\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $3", + "query": "UPDATE volume SET lease_until = NULL, leased_by = NULL, generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $3", "describe": { "columns": [], "parameters": { @@ -12,5 +12,5 @@ }, "nullable": [] }, - "hash": "7ce06d4f623932fce12352be3a09ba8973a2ef1defa36c6d46d9c1c6406a7c33" + "hash": "85ac712e057207d1db48303925b2ca08479830f6de789cbc64661509fccba9ce" } diff --git a/backend/.sqlx/query-8aca507d5a1a548ddce49244b1222bbca953b9436f3b9541677e664c84d443ed.json b/backend/.sqlx/query-8aca507d5a1a548ddce49244b1222bbca953b9436f3b9541677e664c84d443ed.json new file mode 100644 index 0000000000..399d21acaa --- /dev/null +++ b/backend/.sqlx/query-8aca507d5a1a548ddce49244b1222bbca953b9436f3b9541677e664c84d443ed.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE app SET policy = jsonb_set(policy, '{execution_mode}', '\"publisher\"')\n WHERE workspace_id = $1 AND policy->>'execution_mode' = 'anonymous'", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "8aca507d5a1a548ddce49244b1222bbca953b9436f3b9541677e664c84d443ed" +} diff --git a/backend/.sqlx/query-8ff195fecd76e8cffaa4d132832ad21622f0e7ac0ab794e274e780f02902f739.json b/backend/.sqlx/query-8ff195fecd76e8cffaa4d132832ad21622f0e7ac0ab794e274e780f02902f739.json new file mode 100644 index 0000000000..a757b7cfb3 --- /dev/null +++ b/backend/.sqlx/query-8ff195fecd76e8cffaa4d132832ad21622f0e7ac0ab794e274e780f02902f739.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT count(*) AS \"count!\" FROM autoscaling_decision WHERE worker_group = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count!", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "8ff195fecd76e8cffaa4d132832ad21622f0e7ac0ab794e274e780f02902f739" +} diff --git a/backend/.sqlx/query-9008f9abb70a9a07e38acb20bea6a710d0efd77dac4aedeb88d72240e816530b.json b/backend/.sqlx/query-9008f9abb70a9a07e38acb20bea6a710d0efd77dac4aedeb88d72240e816530b.json deleted file mode 100644 index 758da55ad2..0000000000 --- a/backend/.sqlx/query-9008f9abb70a9a07e38acb20bea6a710d0efd77dac4aedeb88d72240e816530b.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT\n j.args as \"args: Json>>\",\n js.flow_status as \"flow_status: Json\",\n j.runnable_path\n FROM v2_job_status js\n INNER JOIN v2_job j ON j.id = js.id\n WHERE js.id = $1\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "args: Json>>", - "type_info": "Jsonb" - }, - { - "ordinal": 1, - "name": "flow_status: Json", - "type_info": "Jsonb" - }, - { - "ordinal": 2, - "name": "runnable_path", - "type_info": "Varchar" - } - ], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [ - true, - true, - true - ] - }, - "hash": "9008f9abb70a9a07e38acb20bea6a710d0efd77dac4aedeb88d72240e816530b" -} diff --git a/backend/.sqlx/query-986c34ebe12210fa1050503f58043374689ef711a282e9d8c7e059d539c6f3a7.json b/backend/.sqlx/query-986c34ebe12210fa1050503f58043374689ef711a282e9d8c7e059d539c6f3a7.json new file mode 100644 index 0000000000..5047f88f9e --- /dev/null +++ b/backend/.sqlx/query-986c34ebe12210fa1050503f58043374689ef711a282e9d8c7e059d539c6f3a7.json @@ -0,0 +1,65 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM draft\n WHERE workspace_id = $1 AND email = $2\n AND (typ::text, path) IN (SELECT * FROM unnest($3::text[], $4::text[]))\n RETURNING typ AS \"typ: UserDraftItemKind\", path", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "typ: UserDraftItemKind", + "type_info": { + "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" + ] + } + } + } + }, + { + "ordinal": 1, + "name": "path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "TextArray", + "TextArray" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "986c34ebe12210fa1050503f58043374689ef711a282e9d8c7e059d539c6f3a7" +} diff --git a/backend/.sqlx/query-9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab.json b/backend/.sqlx/query-9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab.json new file mode 100644 index 0000000000..13f1afb64b --- /dev/null +++ b/backend/.sqlx/query-9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT now() AS \"now!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "now!", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab" +} diff --git a/backend/.sqlx/query-9b25b49ef8a8b4d80ed2a1ce7b49a288037238f34bd6b951e128ee58fc3da93d.json b/backend/.sqlx/query-9b25b49ef8a8b4d80ed2a1ce7b49a288037238f34bd6b951e128ee58fc3da93d.json new file mode 100644 index 0000000000..4ed41a6797 --- /dev/null +++ b/backend/.sqlx/query-9b25b49ef8a8b4d80ed2a1ce7b49a288037238f34bd6b951e128ee58fc3da93d.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO v2_job (id, workspace_id, kind, parent_job, flow_step_id)\n VALUES ($1, $2, 'aiagent', $3, 'a')", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "9b25b49ef8a8b4d80ed2a1ce7b49a288037238f34bd6b951e128ee58fc3da93d" +} diff --git a/backend/.sqlx/query-9e2810312302b36d3b4d761481c00296ee84c9536228496e19b4ec5df1781bc5.json b/backend/.sqlx/query-9e2810312302b36d3b4d761481c00296ee84c9536228496e19b4ec5df1781bc5.json deleted file mode 100644 index 70df593afe..0000000000 --- a/backend/.sqlx/query-9e2810312302b36d3b4d761481c00296ee84c9536228496e19b4ec5df1781bc5.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT COUNT(*) as count, \n MIN(scheduled_for) as oldest_job\n FROM v2_job_queue \n WHERE tag = $1 \n AND scheduled_for <= NOW() - $2::interval \n AND running = false\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "count", - "type_info": "Int8" - }, - { - "ordinal": 1, - "name": "oldest_job", - "type_info": "Timestamptz" - } - ], - "parameters": { - "Left": [ - "Text", - "Interval" - ] - }, - "nullable": [ - null, - null - ] - }, - "hash": "9e2810312302b36d3b4d761481c00296ee84c9536228496e19b4ec5df1781bc5" -} diff --git a/backend/.sqlx/query-9f729dd19fa4155d769eec3ed55ef0b15539aa9c0fef1559820384aa7864056b.json b/backend/.sqlx/query-9f729dd19fa4155d769eec3ed55ef0b15539aa9c0fef1559820384aa7864056b.json new file mode 100644 index 0000000000..8eef569203 --- /dev/null +++ b/backend/.sqlx/query-9f729dd19fa4155d769eec3ed55ef0b15539aa9c0fef1559820384aa7864056b.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_status SET\n flow_status = jsonb_set(\n flow_status,\n array['modules', $2::int::TEXT, 'agent_actions_success'],\n (\n SELECT jsonb_agg(CASE WHEN e = 'null'::jsonb THEN 'false'::jsonb ELSE e END\n ORDER BY i)\n FROM jsonb_array_elements(\n flow_status->'modules'->$2::int->'agent_actions_success'\n ) WITH ORDINALITY AS t(e, i)\n )\n )\n WHERE id = $1\n AND flow_status->'modules'->$2::int->'agent_actions_success' @> '[null]'::jsonb", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Int4" + ] + }, + "nullable": [] + }, + "hash": "9f729dd19fa4155d769eec3ed55ef0b15539aa9c0fef1559820384aa7864056b" +} diff --git a/backend/.sqlx/query-a26528bf01138bfad0c4989c04fd74e3c0aacd9913b7524edcf69f58115875fc.json b/backend/.sqlx/query-a26528bf01138bfad0c4989c04fd74e3c0aacd9913b7524edcf69f58115875fc.json new file mode 100644 index 0000000000..cc4a9ed412 --- /dev/null +++ b/backend/.sqlx/query-a26528bf01138bfad0c4989c04fd74e3c0aacd9913b7524edcf69f58115875fc.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO volume (workspace_id, name, size_bytes, created_by, lease_until, leased_by, generation)\n VALUES ('test-workspace', 'test-vol', 0, 'test-user', now() + interval '1 hour', 'other-worker', 1)", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "a26528bf01138bfad0c4989c04fd74e3c0aacd9913b7524edcf69f58115875fc" +} diff --git a/backend/.sqlx/query-ab6c20641004ad0a93e379cd2287035261318b5c8401059c1c2c73a1b7e62e8b.json b/backend/.sqlx/query-ab6c20641004ad0a93e379cd2287035261318b5c8401059c1c2c73a1b7e62e8b.json new file mode 100644 index 0000000000..bd4d03780c --- /dev/null +++ b/backend/.sqlx/query-ab6c20641004ad0a93e379cd2287035261318b5c8401059c1c2c73a1b7e62e8b.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM draft\n WHERE workspace_id = $1 AND email = $2\n AND (typ::text, path) IN (SELECT * FROM unnest($3::text[], $4::text[]))", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "TextArray", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "ab6c20641004ad0a93e379cd2287035261318b5c8401059c1c2c73a1b7e62e8b" +} diff --git a/backend/.sqlx/query-abeb5bbbcf73a5859deb247c55763b88fb904c85b6248e5326cc0316efd645d9.json b/backend/.sqlx/query-abeb5bbbcf73a5859deb247c55763b88fb904c85b6248e5326cc0316efd645d9.json new file mode 100644 index 0000000000..5eccbd4844 --- /dev/null +++ b/backend/.sqlx/query-abeb5bbbcf73a5859deb247c55763b88fb904c85b6248e5326cc0316efd645d9.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id, status IN ('success', 'skipped') AS \"success!\", result AS \"result: Json>\"\n FROM v2_job_completed WHERE workspace_id = $1 AND id = ANY($2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "success!", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "result: Json>", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text", + "UuidArray" + ] + }, + "nullable": [ + false, + null, + true + ] + }, + "hash": "abeb5bbbcf73a5859deb247c55763b88fb904c85b6248e5326cc0316efd645d9" +} diff --git a/backend/.sqlx/query-ac1007f6bdd93ebe9cebd9f1c541d73d17533f1887021374451e3b6e4803c67b.json b/backend/.sqlx/query-ac1007f6bdd93ebe9cebd9f1c541d73d17533f1887021374451e3b6e4803c67b.json new file mode 100644 index 0000000000..aa4b1eb9b8 --- /dev/null +++ b/backend/.sqlx/query-ac1007f6bdd93ebe9cebd9f1c541d73d17533f1887021374451e3b6e4803c67b.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH RECURSIVE up(id, parent, start, depth) AS (\n SELECT id, parent_workspace_id, id, 0 FROM workspace\n WHERE id IN ($1, $2) AND deleted = false\n UNION ALL\n SELECT w.id, w.parent_workspace_id, up.start, up.depth + 1\n FROM workspace w JOIN up ON w.id = up.parent\n WHERE up.depth < 64\n )\n SELECT (SELECT id FROM up WHERE start = $1 AND parent IS NULL)\n = (SELECT id FROM up WHERE start = $2 AND parent IS NULL) AS \"same\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "same", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Varchar", + "Varchar" + ] + }, + "nullable": [ + null + ] + }, + "hash": "ac1007f6bdd93ebe9cebd9f1c541d73d17533f1887021374451e3b6e4803c67b" +} diff --git a/backend/.sqlx/query-9662f1e304124fa52db4aa1e80e03b2601630f2d31458bdaf70c2702b2998d89.json b/backend/.sqlx/query-b0350f074557a476882697046c3573d6ac532b374d9b2470322f70b875eaec87.json similarity index 55% rename from backend/.sqlx/query-9662f1e304124fa52db4aa1e80e03b2601630f2d31458bdaf70c2702b2998d89.json rename to backend/.sqlx/query-b0350f074557a476882697046c3573d6ac532b374d9b2470322f70b875eaec87.json index fc33fd7373..a44f2a87f1 100644 --- a/backend/.sqlx/query-9662f1e304124fa52db4aa1e80e03b2601630f2d31458bdaf70c2702b2998d89.json +++ b/backend/.sqlx/query-b0350f074557a476882697046c3573d6ac532b374d9b2470322f70b875eaec87.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE volume SET lease_until = NULL, leased_by = NULL\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $3", + "query": "UPDATE volume SET lease_until = NULL, leased_by = NULL, generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $3", "describe": { "columns": [], "parameters": { @@ -12,5 +12,5 @@ }, "nullable": [] }, - "hash": "9662f1e304124fa52db4aa1e80e03b2601630f2d31458bdaf70c2702b2998d89" + "hash": "b0350f074557a476882697046c3573d6ac532b374d9b2470322f70b875eaec87" } diff --git a/backend/.sqlx/query-b0e6fb018738a20844572f18cf6fa269100e1bab92ca31b5db3e67a4d7260405.json b/backend/.sqlx/query-b0e6fb018738a20844572f18cf6fa269100e1bab92ca31b5db3e67a4d7260405.json new file mode 100644 index 0000000000..a796c5594f --- /dev/null +++ b/backend/.sqlx/query-b0e6fb018738a20844572f18cf6fa269100e1bab92ca31b5db3e67a4d7260405.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO ai_memory_turn (workspace_id, memory_id, job_id) VALUES ($1, $2, $3)\n ON CONFLICT (workspace_id, memory_id) DO NOTHING RETURNING job_id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "job_id", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Varchar", + "Uuid", + "Uuid" + ] + }, + "nullable": [ + false + ] + }, + "hash": "b0e6fb018738a20844572f18cf6fa269100e1bab92ca31b5db3e67a4d7260405" +} diff --git a/backend/.sqlx/query-b43d739234309a9341ddd9b18db229a409ffd8c1f96bb07904333bdb94670b52.json b/backend/.sqlx/query-b43d739234309a9341ddd9b18db229a409ffd8c1f96bb07904333bdb94670b52.json new file mode 100644 index 0000000000..8d3c392e8b --- /dev/null +++ b/backend/.sqlx/query-b43d739234309a9341ddd9b18db229a409ffd8c1f96bb07904333bdb94670b52.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO ai_shared_session_opened (share_id, email) VALUES ($1, $2)\n ON CONFLICT (share_id, email) DO UPDATE SET opened_at = now()", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "b43d739234309a9341ddd9b18db229a409ffd8c1f96bb07904333bdb94670b52" +} diff --git a/backend/.sqlx/query-28df7bbe1f54f69640bc76def9e580b4c7ba25f279644e3233b63f4f6db0ad98.json b/backend/.sqlx/query-b6d05e743b558e82bca080ab119aef7949ceae08e71a0191ce185420e037913d.json similarity index 56% rename from backend/.sqlx/query-28df7bbe1f54f69640bc76def9e580b4c7ba25f279644e3233b63f4f6db0ad98.json rename to backend/.sqlx/query-b6d05e743b558e82bca080ab119aef7949ceae08e71a0191ce185420e037913d.json index 2010b40667..e294689ba8 100644 --- a/backend/.sqlx/query-28df7bbe1f54f69640bc76def9e580b4c7ba25f279644e3233b63f4f6db0ad98.json +++ b/backend/.sqlx/query-b6d05e743b558e82bca080ab119aef7949ceae08e71a0191ce185420e037913d.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE volume SET lease_until = NULL, leased_by = NULL\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $3", + "query": "UPDATE volume SET lease_until = NULL, leased_by = NULL, generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $3", "describe": { "columns": [], "parameters": { @@ -12,5 +12,5 @@ }, "nullable": [] }, - "hash": "28df7bbe1f54f69640bc76def9e580b4c7ba25f279644e3233b63f4f6db0ad98" + "hash": "b6d05e743b558e82bca080ab119aef7949ceae08e71a0191ce185420e037913d" } diff --git a/backend/.sqlx/query-b951a9ebcac1ac5e4fe4f763bafcc95db906a50d063585be8c4e34c1a233f2b1.json b/backend/.sqlx/query-b951a9ebcac1ac5e4fe4f763bafcc95db906a50d063585be8c4e34c1a233f2b1.json new file mode 100644 index 0000000000..797ba4c47d --- /dev/null +++ b/backend/.sqlx/query-b951a9ebcac1ac5e4fe4f763bafcc95db906a50d063585be8c4e34c1a233f2b1.json @@ -0,0 +1,71 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT typ AS \"typ: UserDraftItemKind\", path, value::text AS \"value!\" FROM draft\n WHERE workspace_id = $1 AND email = $2\n AND (typ::text, path) IN (SELECT * FROM unnest($3::text[], $4::text[]))\n FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "typ: UserDraftItemKind", + "type_info": { + "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" + ] + } + } + } + }, + { + "ordinal": 1, + "name": "path", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "value!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "TextArray", + "TextArray" + ] + }, + "nullable": [ + false, + false, + null + ] + }, + "hash": "b951a9ebcac1ac5e4fe4f763bafcc95db906a50d063585be8c4e34c1a233f2b1" +} diff --git a/backend/.sqlx/query-b9869f04e03be64187b0780e261af2a6e53bbc7875a636eafadb20667d883879.json b/backend/.sqlx/query-b9869f04e03be64187b0780e261af2a6e53bbc7875a636eafadb20667d883879.json new file mode 100644 index 0000000000..6b5eb18ba5 --- /dev/null +++ b/backend/.sqlx/query-b9869f04e03be64187b0780e261af2a6e53bbc7875a636eafadb20667d883879.json @@ -0,0 +1,18 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job SET parent_job = $2, root_job = $3, flow_innermost_root_job = $4\n WHERE id = ANY($1) AND workspace_id = $5", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "UuidArray", + "Uuid", + "Uuid", + "Uuid", + "Text" + ] + }, + "nullable": [] + }, + "hash": "b9869f04e03be64187b0780e261af2a6e53bbc7875a636eafadb20667d883879" +} diff --git a/backend/.sqlx/query-be2bcf0fb9a3c2fa50ad43d4a2d766f073e96a25d307db70fa6560a1f40b4602.json b/backend/.sqlx/query-be2bcf0fb9a3c2fa50ad43d4a2d766f073e96a25d307db70fa6560a1f40b4602.json new file mode 100644 index 0000000000..88f45586b3 --- /dev/null +++ b/backend/.sqlx/query-be2bcf0fb9a3c2fa50ad43d4a2d766f073e96a25d307db70fa6560a1f40b4602.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO ai_agent_checkpoint (job_id, workspace_id, checkpoint, waiting_on)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (job_id) DO UPDATE\n SET checkpoint = EXCLUDED.checkpoint, waiting_on = EXCLUDED.waiting_on", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Jsonb", + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "be2bcf0fb9a3c2fa50ad43d4a2d766f073e96a25d307db70fa6560a1f40b4602" +} diff --git a/backend/.sqlx/query-beca1893fb61eb1d825af909345ea816ca2b0f6cb8b557dcbf9b0a538fb720f5.json b/backend/.sqlx/query-beca1893fb61eb1d825af909345ea816ca2b0f6cb8b557dcbf9b0a538fb720f5.json new file mode 100644 index 0000000000..28d36fea0a --- /dev/null +++ b/backend/.sqlx/query-beca1893fb61eb1d825af909345ea816ca2b0f6cb8b557dcbf9b0a538fb720f5.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM v2_job_completed WHERE id = ANY($1)) AS \"finished!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "finished!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + null + ] + }, + "hash": "beca1893fb61eb1d825af909345ea816ca2b0f6cb8b557dcbf9b0a538fb720f5" +} diff --git a/backend/.sqlx/query-c57072d3a127884226ab21b6bda868cdf383eeff4b6c66879ca97df949696886.json b/backend/.sqlx/query-c57072d3a127884226ab21b6bda868cdf383eeff4b6c66879ca97df949696886.json new file mode 100644 index 0000000000..0d1f13e6d8 --- /dev/null +++ b/backend/.sqlx/query-c57072d3a127884226ab21b6bda868cdf383eeff4b6c66879ca97df949696886.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO github_app_repo_approval (workspace_id, path, url)\n SELECT workspace_id, path, value->>'url' FROM resource\n WHERE workspace_id = $1 AND path = $2\n AND value->'is_github_app' = 'true'::jsonb\n AND left(value->>'url', 1) <> '$'", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "c57072d3a127884226ab21b6bda868cdf383eeff4b6c66879ca97df949696886" +} diff --git a/backend/.sqlx/query-c806b27348b384f2a84a27f24ca300efb92b0c223a70c68eb5eaea3cddcba857.json b/backend/.sqlx/query-c806b27348b384f2a84a27f24ca300efb92b0c223a70c68eb5eaea3cddcba857.json new file mode 100644 index 0000000000..7daa44beb3 --- /dev/null +++ b/backend/.sqlx/query-c806b27348b384f2a84a27f24ca300efb92b0c223a70c68eb5eaea3cddcba857.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT test_script_path, tested_item_path, tested_item_kind, has_wildcard AS \"has_wildcard!\" FROM ci_test_reference WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "test_script_path", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "tested_item_path", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "tested_item_kind", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "has_wildcard!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false, + false, + true + ] + }, + "hash": "c806b27348b384f2a84a27f24ca300efb92b0c223a70c68eb5eaea3cddcba857" +} diff --git a/backend/.sqlx/query-cbb90b20bef5904ff3c89a65a3662c01730c46882b15a02c22e48eeda24903e1.json b/backend/.sqlx/query-cbb90b20bef5904ff3c89a65a3662c01730c46882b15a02c22e48eeda24903e1.json new file mode 100644 index 0000000000..7d3308a8ad --- /dev/null +++ b/backend/.sqlx/query-cbb90b20bef5904ff3c89a65a3662c01730c46882b15a02c22e48eeda24903e1.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH decisions AS (\n DELETE FROM autoscaling_decision WHERE recorded_at <= now() - interval '48 hours'\n )\n DELETE FROM autoscaling_recording WHERE until <= now()", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "cbb90b20bef5904ff3c89a65a3662c01730c46882b15a02c22e48eeda24903e1" +} diff --git a/backend/.sqlx/query-cd5cdad3449dd5f58c88d3a7b99158da707d8f23513c155deb430b702d932263.json b/backend/.sqlx/query-cd5cdad3449dd5f58c88d3a7b99158da707d8f23513c155deb430b702d932263.json new file mode 100644 index 0000000000..aeba3d96be --- /dev/null +++ b/backend/.sqlx/query-cd5cdad3449dd5f58c88d3a7b99158da707d8f23513c155deb430b702d932263.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT leased_by FROM volume WHERE workspace_id = 'test-workspace' AND name = 'test-vol'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "leased_by", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + true + ] + }, + "hash": "cd5cdad3449dd5f58c88d3a7b99158da707d8f23513c155deb430b702d932263" +} diff --git a/backend/.sqlx/query-ce5a5c8798e7b525b8dd10f16c63aaca0b6e002c32d33dd1e6c3b03e5e6b18d7.json b/backend/.sqlx/query-ce5a5c8798e7b525b8dd10f16c63aaca0b6e002c32d33dd1e6c3b03e5e6b18d7.json new file mode 100644 index 0000000000..4ef8280599 --- /dev/null +++ b/backend/.sqlx/query-ce5a5c8798e7b525b8dd10f16c63aaca0b6e002c32d33dd1e6c3b03e5e6b18d7.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM ai_shared_session_opened o\n USING ai_shared_session s\n WHERE o.share_id = s.id AND s.workspace_id = $1 AND o.share_id = $2 AND o.email = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Uuid", + "Text" + ] + }, + "nullable": [] + }, + "hash": "ce5a5c8798e7b525b8dd10f16c63aaca0b6e002c32d33dd1e6c3b03e5e6b18d7" +} diff --git a/backend/.sqlx/query-ceb0b3574d9e409a04dadb32ab92233c728ff7bbe5bb1d50897afcd6d6367415.json b/backend/.sqlx/query-ceb0b3574d9e409a04dadb32ab92233c728ff7bbe5bb1d50897afcd6d6367415.json new file mode 100644 index 0000000000..bdb6dc392f --- /dev/null +++ b/backend/.sqlx/query-ceb0b3574d9e409a04dadb32ab92233c728ff7bbe5bb1d50897afcd6d6367415.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT username, super_admin FROM password WHERE email = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "super_admin", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true, + false + ] + }, + "hash": "ceb0b3574d9e409a04dadb32ab92233c728ff7bbe5bb1d50897afcd6d6367415" +} diff --git a/backend/.sqlx/query-cfe8cc359df270364233f97575c1efd5442136287b7939444de6c86d81d11f4e.json b/backend/.sqlx/query-cfe8cc359df270364233f97575c1efd5442136287b7939444de6c86d81d11f4e.json new file mode 100644 index 0000000000..bb1488a1e9 --- /dev/null +++ b/backend/.sqlx/query-cfe8cc359df270364233f97575c1efd5442136287b7939444de6c86d81d11f4e.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for)\n VALUES ($1, $2, now()), ($3, $2, now())", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "cfe8cc359df270364233f97575c1efd5442136287b7939444de6c86d81d11f4e" +} diff --git a/backend/.sqlx/query-d087cfc975f26094f8e2084504cec8c2a3e78f32a0f14872f4076e0f0a9df607.json b/backend/.sqlx/query-d087cfc975f26094f8e2084504cec8c2a3e78f32a0f14872f4076e0f0a9df607.json new file mode 100644 index 0000000000..d483ccda9a --- /dev/null +++ b/backend/.sqlx/query-d087cfc975f26094f8e2084504cec8c2a3e78f32a0f14872f4076e0f0a9df607.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_status SET flow_status = jsonb_set(flow_status, '{test_subflows}', $2)\n WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Jsonb" + ] + }, + "nullable": [] + }, + "hash": "d087cfc975f26094f8e2084504cec8c2a3e78f32a0f14872f4076e0f0a9df607" +} diff --git a/backend/.sqlx/query-d492e188a54842b4e7580e6668e894a966bb72705e6b29eeb790bda6b4d64f4e.json b/backend/.sqlx/query-d492e188a54842b4e7580e6668e894a966bb72705e6b29eeb790bda6b4d64f4e.json new file mode 100644 index 0000000000..451dac97ff --- /dev/null +++ b/backend/.sqlx/query-d492e188a54842b4e7580e6668e894a966bb72705e6b29eeb790bda6b4d64f4e.json @@ -0,0 +1,72 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT s.id, s.session_id, s.email, s.name, s.is_public, s.message_count, s.created_by,\n s.shared_at, o.opened_at AS \"opened_at?\"\n FROM ai_shared_session s\n LEFT JOIN ai_shared_session_opened o ON o.share_id = s.id AND o.email = $2\n WHERE s.workspace_id = $1 AND (s.email = $2 OR o.share_id IS NOT NULL)\n ORDER BY COALESCE(o.opened_at, s.shared_at) DESC\n LIMIT $3", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "session_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 4, + "name": "is_public", + "type_info": "Bool" + }, + { + "ordinal": 5, + "name": "message_count", + "type_info": "Int4" + }, + { + "ordinal": 6, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "shared_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 8, + "name": "opened_at?", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "d492e188a54842b4e7580e6668e894a966bb72705e6b29eeb790bda6b4d64f4e" +} diff --git a/backend/.sqlx/query-d4c55e1c6ad3e236bd0a42440275c86a422c0ae871569f4c02ba7993b9f90e92.json b/backend/.sqlx/query-d4c55e1c6ad3e236bd0a42440275c86a422c0ae871569f4c02ba7993b9f90e92.json new file mode 100644 index 0000000000..3e7b411ad1 --- /dev/null +++ b/backend/.sqlx/query-d4c55e1c6ad3e236bd0a42440275c86a422c0ae871569f4c02ba7993b9f90e92.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for) VALUES ($1, $2, now())", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "d4c55e1c6ad3e236bd0a42440275c86a422c0ae871569f4c02ba7993b9f90e92" +} diff --git a/backend/.sqlx/query-dee2bb7623574d5cb38cba0f1687a7d2e030000f7a881eff50c307d77e44448e.json b/backend/.sqlx/query-dee2bb7623574d5cb38cba0f1687a7d2e030000f7a881eff50c307d77e44448e.json new file mode 100644 index 0000000000..9731bfadb1 --- /dev/null +++ b/backend/.sqlx/query-dee2bb7623574d5cb38cba0f1687a7d2e030000f7a881eff50c307d77e44448e.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT t.job_id, j.created_by, j.tag FROM ai_memory_turn t\n JOIN v2_job_queue q ON q.id = t.job_id\n JOIN v2_job j ON j.id = t.job_id\n WHERE t.workspace_id = $1 AND t.memory_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "job_id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "tag", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Uuid" + ] + }, + "nullable": [ + false, + false, + false + ] + }, + "hash": "dee2bb7623574d5cb38cba0f1687a7d2e030000f7a881eff50c307d77e44448e" +} diff --git a/backend/.sqlx/query-dfe0a2a6e4ab88d5341415bdc19a6982a22cd119e5e1dbe2b6149883e71a0066.json b/backend/.sqlx/query-dfe0a2a6e4ab88d5341415bdc19a6982a22cd119e5e1dbe2b6149883e71a0066.json new file mode 100644 index 0000000000..492b6f3021 --- /dev/null +++ b/backend/.sqlx/query-dfe0a2a6e4ab88d5341415bdc19a6982a22cd119e5e1dbe2b6149883e71a0066.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO volume (workspace_id, name, size_bytes, created_by, lease_until, leased_by, generation)\n VALUES ('test-workspace', 'test-vol', 0, 'test-user', now() + make_interval(secs => $1), 'other-worker', $2)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Float8", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "dfe0a2a6e4ab88d5341415bdc19a6982a22cd119e5e1dbe2b6149883e71a0066" +} diff --git a/backend/.sqlx/query-e0838b093a54f1f9735452f62068612d76144ac859fc904d882a58d990de952d.json b/backend/.sqlx/query-e0838b093a54f1f9735452f62068612d76144ac859fc904d882a58d990de952d.json new file mode 100644 index 0000000000..2a9eab8307 --- /dev/null +++ b/backend/.sqlx/query-e0838b093a54f1f9735452f62068612d76144ac859fc904d882a58d990de952d.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT generation FROM volume WHERE workspace_id = $1 AND name = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "generation", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "e0838b093a54f1f9735452f62068612d76144ac859fc904d882a58d990de952d" +} diff --git a/backend/.sqlx/query-e6140682ebc65083f48714ab3299fdb239ef507e23003db03aff7d35b02c540b.json b/backend/.sqlx/query-e6140682ebc65083f48714ab3299fdb239ef507e23003db03aff7d35b02c540b.json deleted file mode 100644 index f218653d46..0000000000 --- a/backend/.sqlx/query-e6140682ebc65083f48714ab3299fdb239ef507e23003db03aff7d35b02c540b.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO draft (workspace_id, path, typ, value, created_at, email, base)\n SELECT $2, path, typ,\n to_json(\n CASE WHEN typ IN ('script', 'flow') THEN clean - 'on_behalf_of' ELSE clean END\n - CASE WHEN typ = 'flow' THEN 'version_id'\n WHEN typ IN ('app', 'raw_app') THEN 'parent_version'\n ELSE '' END\n ),\n created_at, email,\n CASE WHEN typ = 'script' THEN base END\n FROM (\n SELECT d.path, d.typ, d.created_at, d.email, d.base,\n replace(replace(replace(d.value::text, chr(92) || chr(92), chr(1)), chr(92) || 'u0000', ''), chr(1), chr(92) || chr(92))::jsonb AS clean\n FROM draft d\n WHERE d.workspace_id = $1 AND (d.email = $3 OR d.email IS NULL)\n ) s", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "Varchar", - "Text" - ] - }, - "nullable": [] - }, - "hash": "e6140682ebc65083f48714ab3299fdb239ef507e23003db03aff7d35b02c540b" -} diff --git a/backend/.sqlx/query-e63877925691e80d722f5fc4384c0ac00f6f4389224dca3feee1b879d4009f81.json b/backend/.sqlx/query-e63877925691e80d722f5fc4384c0ac00f6f4389224dca3feee1b879d4009f81.json new file mode 100644 index 0000000000..dd1c182641 --- /dev/null +++ b/backend/.sqlx/query-e63877925691e80d722f5fc4384c0ac00f6f4389224dca3feee1b879d4009f81.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_queue q SET suspend = 0\n FROM ai_agent_checkpoint c\n WHERE c.waiting_on <> '{}' AND q.id = c.job_id\n AND q.suspend > 0 AND q.suspend_until IS NOT NULL\n AND EXISTS (SELECT 1 FROM v2_job_completed jc WHERE jc.id = ANY(c.waiting_on))", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "e63877925691e80d722f5fc4384c0ac00f6f4389224dca3feee1b879d4009f81" +} diff --git a/backend/.sqlx/query-e86adb3b43a814b6f67d7c4087f5fdb6adcc1298bc917ef89f09b787dc8ea942.json b/backend/.sqlx/query-e86adb3b43a814b6f67d7c4087f5fdb6adcc1298bc917ef89f09b787dc8ea942.json new file mode 100644 index 0000000000..19f6429436 --- /dev/null +++ b/backend/.sqlx/query-e86adb3b43a814b6f67d7c4087f5fdb6adcc1298bc917ef89f09b787dc8ea942.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT worker_group FROM autoscaling_recording WHERE until > now()", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "worker_group", + "type_info": "Text" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false + ] + }, + "hash": "e86adb3b43a814b6f67d7c4087f5fdb6adcc1298bc917ef89f09b787dc8ea942" +} diff --git a/backend/.sqlx/query-e938951c0c6ddd268db7a0dc69484446d4e869951188a0add41036d4fd095298.json b/backend/.sqlx/query-e938951c0c6ddd268db7a0dc69484446d4e869951188a0add41036d4fd095298.json new file mode 100644 index 0000000000..b135e3226e --- /dev/null +++ b/backend/.sqlx/query-e938951c0c6ddd268db7a0dc69484446d4e869951188a0add41036d4fd095298.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT generation, coalesce(lease_until > now(), false) AS \"write_live!\"\n FROM volume WHERE workspace_id = $1 AND name = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "generation", + "type_info": "Int8" + }, + { + "ordinal": 1, + "name": "write_live!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "e938951c0c6ddd268db7a0dc69484446d4e869951188a0add41036d4fd095298" +} diff --git a/backend/.sqlx/query-e99555474694f563991558f8f1447c2eeec0ece06b69d730c6b3d3dffcafeb26.json b/backend/.sqlx/query-e99555474694f563991558f8f1447c2eeec0ece06b69d730c6b3d3dffcafeb26.json new file mode 100644 index 0000000000..6632183e9c --- /dev/null +++ b/backend/.sqlx/query-e99555474694f563991558f8f1447c2eeec0ece06b69d730c6b3d3dffcafeb26.json @@ -0,0 +1,25 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO volume (workspace_id, name, size_bytes, created_by, lease_until, leased_by)\n VALUES ($1, $2, 0, $3, now() + interval '60 seconds', $4)\n ON CONFLICT (workspace_id, name) DO UPDATE\n SET lease_until = now() + interval '60 seconds', leased_by = $4,\n generation = volume.generation + volume.generation % 2\n WHERE volume.lease_until IS NULL OR volume.lease_until < now()\n RETURNING name", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Varchar" + ] + }, + "nullable": [ + false + ] + }, + "hash": "e99555474694f563991558f8f1447c2eeec0ece06b69d730c6b3d3dffcafeb26" +} diff --git a/backend/.sqlx/query-ea53847943595074dcff9e8720a157abeca3737dd915c935971f3992e65ba389.json b/backend/.sqlx/query-ea53847943595074dcff9e8720a157abeca3737dd915c935971f3992e65ba389.json new file mode 100644 index 0000000000..6ec2cf7419 --- /dev/null +++ b/backend/.sqlx/query-ea53847943595074dcff9e8720a157abeca3737dd915c935971f3992e65ba389.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM v2_job_queue WHERE id = $1) AS \"queued!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "queued!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "ea53847943595074dcff9e8720a157abeca3737dd915c935971f3992e65ba389" +} diff --git a/backend/.sqlx/query-eb880e5688cf0c4be6fc71034e062eca59d3b850b9181ad04fb5bfcc1f3ed0bb.json b/backend/.sqlx/query-eb880e5688cf0c4be6fc71034e062eca59d3b850b9181ad04fb5bfcc1f3ed0bb.json new file mode 100644 index 0000000000..22ed6390e2 --- /dev/null +++ b/backend/.sqlx/query-eb880e5688cf0c4be6fc71034e062eca59d3b850b9181ad04fb5bfcc1f3ed0bb.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE ai_agent_checkpoint\n SET checkpoint = jsonb_set(checkpoint, '{handed_over}', 'true'), waiting_on = '{}'\n WHERE job_id = ANY($1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [] + }, + "hash": "eb880e5688cf0c4be6fc71034e062eca59d3b850b9181ad04fb5bfcc1f3ed0bb" +} diff --git a/backend/.sqlx/query-75a03e9e4cba350a104e2e3a95de919cd25538c0b433bc29bb052c7a7b8568ca.json b/backend/.sqlx/query-f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea.json similarity index 60% rename from backend/.sqlx/query-75a03e9e4cba350a104e2e3a95de919cd25538c0b433bc29bb052c7a7b8568ca.json rename to backend/.sqlx/query-f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea.json index 3df9c6c195..ca7a719231 100644 --- a/backend/.sqlx/query-75a03e9e4cba350a104e2e3a95de919cd25538c0b433bc29bb052c7a7b8568ca.json +++ b/backend/.sqlx/query-f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), last_used_at = now(),\n lease_until = NULL, leased_by = NULL\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $5", + "query": "UPDATE volume\n SET size_bytes = $3, file_count = $4,\n updated_at = now(), last_used_at = now(),\n lease_until = NULL, leased_by = NULL,\n generation = generation + generation % 2\n WHERE workspace_id = $1 AND name = $2 AND leased_by = $5", "describe": { "columns": [], "parameters": { @@ -14,5 +14,5 @@ }, "nullable": [] }, - "hash": "75a03e9e4cba350a104e2e3a95de919cd25538c0b433bc29bb052c7a7b8568ca" + "hash": "f5946a3968df859f668d6197562c10024ffc24f108ca48d5b3fa98e489d931ea" } diff --git a/backend/.sqlx/query-f59e3a5538089295b20288b293d862db9fa060c93725bb7380d59dfa1c09eab7.json b/backend/.sqlx/query-f59e3a5538089295b20288b293d862db9fa060c93725bb7380d59dfa1c09eab7.json new file mode 100644 index 0000000000..093090f337 --- /dev/null +++ b/backend/.sqlx/query-f59e3a5538089295b20288b293d862db9fa060c93725bb7380d59dfa1c09eab7.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH RECURSIVE tree AS (\n SELECT (b->>'job_id')::uuid AS id\n FROM jsonb_each($1::jsonb) s, jsonb_array_elements(s.value) b\n UNION\n SELECT j.id FROM v2_job j JOIN tree t ON j.parent_job = t.id\n )\n UPDATE v2_job_queue q\n SET canceled_by = 'monitor', scheduled_for = now(), suspend = 0,\n canceled_reason = 'the turn its AI agent was handed to ended before taking it'\n FROM tree WHERE q.id = tree.id AND q.canceled_by IS NULL", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Jsonb" + ] + }, + "nullable": [] + }, + "hash": "f59e3a5538089295b20288b293d862db9fa060c93725bb7380d59dfa1c09eab7" +} diff --git a/backend/.sqlx/query-f688cb133dc6e916ef575d4ea7a55ac041db620c5bd881110efcb8ceb6fd1f8b.json b/backend/.sqlx/query-f688cb133dc6e916ef575d4ea7a55ac041db620c5bd881110efcb8ceb6fd1f8b.json new file mode 100644 index 0000000000..f259d07f73 --- /dev/null +++ b/backend/.sqlx/query-f688cb133dc6e916ef575d4ea7a55ac041db620c5bd881110efcb8ceb6fd1f8b.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM ai_agent_checkpoint c\n WHERE NOT EXISTS (SELECT 1 FROM v2_job_queue q WHERE q.id = c.job_id)", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "f688cb133dc6e916ef575d4ea7a55ac041db620c5bd881110efcb8ceb6fd1f8b" +} diff --git a/backend/.sqlx/query-fbd86b86122ac71607e3f6f286dc35cdff0e273aeee4e1e5ea2293140d14080b.json b/backend/.sqlx/query-fbd86b86122ac71607e3f6f286dc35cdff0e273aeee4e1e5ea2293140d14080b.json new file mode 100644 index 0000000000..c0d992de87 --- /dev/null +++ b/backend/.sqlx/query-fbd86b86122ac71607e3f6f286dc35cdff0e273aeee4e1e5ea2293140d14080b.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT canceled_by FROM v2_job_queue WHERE id = ANY($1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "canceled_by", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "UuidArray" + ] + }, + "nullable": [ + true + ] + }, + "hash": "fbd86b86122ac71607e3f6f286dc35cdff0e273aeee4e1e5ea2293140d14080b" +} diff --git a/backend/.sqlx/query-ffacf78c4cf86ed890ebdce8e408a90c59668b54b4ca1cf688c56a1e3f66bbac.json b/backend/.sqlx/query-ffacf78c4cf86ed890ebdce8e408a90c59668b54b4ca1cf688c56a1e3f66bbac.json new file mode 100644 index 0000000000..ac72e35a8a --- /dev/null +++ b/backend/.sqlx/query-ffacf78c4cf86ed890ebdce8e408a90c59668b54b4ca1cf688c56a1e3f66bbac.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT job_id, handed_jobs FROM ai_memory_turn WHERE workspace_id = $1 AND memory_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "job_id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "handed_jobs", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text", + "Uuid" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "ffacf78c4cf86ed890ebdce8e408a90c59668b54b4ca1cf688c56a1e3f66bbac" +} diff --git a/backend/Cargo.lock b/backend/Cargo.lock index b7b631f218..ca59d29250 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -234,9 +234,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "ar_archive_writer" -version = "0.5.3" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" dependencies = [ "object", ] @@ -405,7 +405,7 @@ dependencies = [ "arrow-data", "arrow-schema", "flatbuffers", - "lz4_flex 0.11.6", + "lz4_flex 0.11.7", ] [[package]] @@ -490,7 +490,7 @@ dependencies = [ "memchr", "num", "regex", - "regex-syntax 0.8.11", + "regex-syntax 0.8.12", ] [[package]] @@ -2111,9 +2111,9 @@ dependencies = [ [[package]] name = "bstr" -version = "1.13.1" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214" dependencies = [ "memchr", "regex-automata", @@ -2131,9 +2131,9 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.20.3" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" dependencies = [ "allocator-api2", ] @@ -2200,9 +2200,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.12.1" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" dependencies = [ "serde", ] @@ -2366,9 +2366,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.11.1" +version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" dependencies = [ "find-msvc-tools", "jobserver", @@ -2492,9 +2492,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.7" +version = "4.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a" dependencies = [ "clap_builder", "clap_derive", @@ -2514,9 +2514,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.6.7" +version = "4.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a" dependencies = [ "heck", "proc-macro2", @@ -2526,9 +2526,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "1.1.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" [[package]] name = "cmake" @@ -2663,9 +2663,9 @@ checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" [[package]] name = "const-oid" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" [[package]] name = "const-random" @@ -3789,7 +3789,7 @@ dependencies = [ "log", "recursive", "regex", - "regex-syntax 0.8.11", + "regex-syntax 0.8.12", ] [[package]] @@ -4141,7 +4141,7 @@ dependencies = [ "hyper-util", "ipnet", "percent-encoding", - "rustls-webpki 0.103.16", + "rustls-webpki 0.103.17", "serde_json", "thiserror 2.0.21", "tokio", @@ -4380,7 +4380,7 @@ dependencies = [ "opentelemetry-semantic-conventions 0.32.1", "opentelemetry_sdk 0.32.1", "pin-project", - "prost 0.14.4", + "prost 0.14.6", "serde", "sys_traits", "thiserror 2.0.21", @@ -4412,7 +4412,7 @@ dependencies = [ "rustls 0.23.40", "rustls-pemfile 2.2.0", "rustls-tokio-stream", - "rustls-webpki 0.103.16", + "rustls-webpki 0.103.17", "serde", "thiserror 2.0.21", "tokio", @@ -4507,7 +4507,7 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" dependencies = [ - "const-oid 0.10.2", + "const-oid 0.10.3", "pem-rfc7468 1.0.0", "zeroize", ] @@ -4744,7 +4744,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid 0.10.2", + "const-oid 0.10.3", "crypto-common 0.2.2", "ctutils", ] @@ -5257,9 +5257,9 @@ dependencies = [ [[package]] name = "errno" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", "windows-sys 0.61.2", @@ -5351,7 +5351,7 @@ checksum = "6e24cb5a94bcae1e5408b0effca5cd7172ea3c5755049c5f3af4cd283a165298" dependencies = [ "bit-set", "regex-automata", - "regex-syntax 0.8.11", + "regex-syntax 0.8.12", ] [[package]] @@ -5362,7 +5362,7 @@ checksum = "72cf461f865c862bb7dc573f643dd6a2b6842f7c30b07882b56bd148cc2761b8" dependencies = [ "bit-set", "regex-automata", - "regex-syntax 0.8.11", + "regex-syntax 0.8.12", ] [[package]] @@ -5432,9 +5432,9 @@ checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" [[package]] name = "filetime" -version = "0.2.29" +version = "0.2.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" dependencies = [ "cfg-if", "libc", @@ -6062,7 +6062,7 @@ dependencies = [ "bstr", "log", "regex-automata", - "regex-syntax 0.8.11", + "regex-syntax 0.8.12", ] [[package]] @@ -6778,7 +6778,7 @@ dependencies = [ "tokio", "tokio-rustls 0.26.6", "tower-service", - "webpki-roots 1.0.11", + "webpki-roots 1.0.12", ] [[package]] @@ -7254,9 +7254,9 @@ checksum = "4754a1731458af0443709c9667302793d3f63cc90ec4ba4c8259f2b9515478e5" [[package]] name = "jiff" -version = "0.2.42" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fefca06093eeaed707a905795e68206da0edca4edef23d2a3997a3ddbee462aa" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" dependencies = [ "jiff-core", "jiff-static", @@ -7271,18 +7271,18 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.4" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77a24020db0ee88d1c681d677681bd31f9f4ea189a455425223d52ce4f1508aa" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" dependencies = [ "log", ] [[package]] name = "jiff-static" -version = "0.2.42" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d3213549742662eea1a18e6c5af9be5dfbabeb7611ab71356a54928ec398f0" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" dependencies = [ "jiff-core", "proc-macro2", @@ -7292,9 +7292,9 @@ dependencies = [ [[package]] name = "jiff-tzdb" -version = "0.1.9" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" +checksum = "0980fca2cc272465bd60e82397607ba9f33add9e48defd77923301bbd03808f2" [[package]] name = "jiff-tzdb-platform" @@ -7936,18 +7936,18 @@ dependencies = [ [[package]] name = "lz4_flex" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a" +checksum = "13591d77a9b6d941f7e6fcade7f9dfd9e801308752bde50c0a9bb5852778c22c" dependencies = [ "twox-hash", ] [[package]] name = "lz4_flex" -version = "0.14.0" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" +checksum = "f56455fff36934a9500d69062aec1c77037179b6f0669e4d5d6b72b84722d6a3" [[package]] name = "lzma-sys" @@ -8276,9 +8276,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.4" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -8388,7 +8388,7 @@ dependencies = [ "native-tls", "pem", "percent-encoding", - "rand 0.10.3", + "rand 0.10.4", "serde", "socket2 0.6.5", "thiserror 2.0.21", @@ -8497,9 +8497,9 @@ dependencies = [ [[package]] name = "nix" -version = "0.31.3" +version = "0.31.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +checksum = "2bc81ce8148d3b4f3274da811f11cdd824ae661ee4ef732cdb229825cf5be7f7" dependencies = [ "bitflags 2.13.2", "cfg-if", @@ -9197,7 +9197,7 @@ dependencies = [ "opentelemetry-http 0.32.0", "opentelemetry-proto 0.32.0", "opentelemetry_sdk 0.32.1", - "prost 0.14.4", + "prost 0.14.6", "serde_json", "thiserror 2.0.21", ] @@ -9227,7 +9227,7 @@ dependencies = [ "const-hex", "opentelemetry 0.32.0", "opentelemetry_sdk 0.32.1", - "prost 0.14.4", + "prost 0.14.6", "serde", ] @@ -9516,7 +9516,7 @@ dependencies = [ "futures", "half", "hashbrown 0.15.5", - "lz4_flex 0.11.6", + "lz4_flex 0.11.7", "num", "num-bigint", "object_store", @@ -9830,29 +9830,29 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.13" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +checksum = "a6c2123f4708bbd422630a6dae7c03f678b1ce1f1c99e4c4b3beac69c8174cc9" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.13" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +checksum = "358938fd6df944c1e44bb328b60fb275f13c804aac47ba26a1165d45a3f87756" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.10", ] [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" [[package]] name = "pin-utils" @@ -10048,7 +10048,7 @@ dependencies = [ "hmac 0.13.0", "md-5 0.11.0", "memchr", - "rand 0.10.3", + "rand 0.10.4", "sha2 0.11.1", "stringprep", ] @@ -10272,9 +10272,9 @@ dependencies = [ "chacha20", "core_detect", "num-traits", - "rand 0.10.3", + "rand 0.10.4", "rand_xorshift", - "regex-syntax 0.8.11", + "regex-syntax 0.8.12", "unarray", ] @@ -10290,12 +10290,12 @@ dependencies = [ [[package]] name = "prost" -version = "0.14.4" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" +checksum = "3ef0b569d1d907ab3a28596aee62cf1f61dacb0529a4bedcd8e7460e2d5228b4" dependencies = [ "bytes", - "prost-derive 0.14.4", + "prost-derive 0.14.6", ] [[package]] @@ -10313,12 +10313,12 @@ dependencies = [ [[package]] name = "prost-derive" -version = "0.14.4" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" +checksum = "1ad9c5423459fa2f729b8d9235fab810aa29628b171467744fc86d21460ad70d" dependencies = [ "anyhow", - "itertools 0.14.0", + "itertools 0.15.0", "proc-macro2", "quote", "syn 2.0.119", @@ -10467,7 +10467,7 @@ dependencies = [ "fastbloom", "getrandom 0.4.3", "lru-slab", - "rand 0.10.3", + "rand 0.10.4", "rand_pcg", "ring 0.17.14", "rustc-hash 2.1.3", @@ -10579,9 +10579,9 @@ dependencies = [ [[package]] name = "rand" -version = "0.10.3" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" dependencies = [ "chacha20", "getrandom 0.4.3", @@ -10672,9 +10672,9 @@ dependencies = [ [[package]] name = "rand_pcg" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" dependencies = [ "rand_core 0.10.1", ] @@ -10883,25 +10883,25 @@ dependencies = [ [[package]] name = "regex" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" dependencies = [ "aho-corasick", "memchr", "regex-automata", - "regex-syntax 0.8.11", + "regex-syntax 0.8.12", ] [[package]] name = "regex-automata" -version = "0.4.18" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.11", + "regex-syntax 0.8.12", ] [[package]] @@ -10918,9 +10918,9 @@ checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" [[package]] name = "regex-syntax" -version = "0.8.11" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" [[package]] name = "relative-path" @@ -10986,7 +10986,7 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams 0.4.2", "web-sys", - "webpki-roots 1.0.11", + "webpki-roots 1.0.12", ] [[package]] @@ -11092,7 +11092,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc05fbf560421a0357a750cbe78c7ca19d4923918490daabba313d5dbc871e47" dependencies = [ - "rand 0.10.3", + "rand 0.10.4", ] [[package]] @@ -11190,7 +11190,7 @@ dependencies = [ "oauth2", "pastey", "pin-project-lite", - "rand 0.10.3", + "rand 0.10.4", "reqwest 0.13.5", "rmcp-macros", "schemars 1.2.3", @@ -11209,9 +11209,9 @@ dependencies = [ [[package]] name = "rmcp-macros" -version = "3.9.0" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3140f24a766f80f9ec1607bde85680959a69b83d46fa9ce87dadab7e67ab029" +checksum = "3598e3f36f4af2b5219b133baf7d97a2197039225adc3d4acf3dd8805b5a2aef" dependencies = [ "darling 0.24.1", "proc-macro2", @@ -11568,7 +11568,7 @@ dependencies = [ "once_cell", "ring 0.17.14", "rustls-pki-types", - "rustls-webpki 0.103.16", + "rustls-webpki 0.103.17", "subtle", "zeroize", ] @@ -11583,7 +11583,7 @@ dependencies = [ "rustls 0.23.40", "rustls-native-certs 0.7.3", "rustls-pki-types", - "rustls-webpki 0.103.16", + "rustls-webpki 0.103.17", ] [[package]] @@ -11643,9 +11643,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.15.1" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ "web-time", "zeroize", @@ -11665,7 +11665,7 @@ dependencies = [ "rustls 0.23.40", "rustls-native-certs 0.8.5", "rustls-platform-verifier-android", - "rustls-webpki 0.103.16", + "rustls-webpki 0.103.17", "security-framework 3.7.0", "security-framework-sys", "webpki-root-certs", @@ -11714,9 +11714,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.16" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "aws-lc-rs", "ring 0.17.14", @@ -12530,9 +12530,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.5" +version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" dependencies = [ "serde", ] @@ -13607,9 +13607,9 @@ dependencies = [ [[package]] name = "systemstat" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a583abe520746270ffdbdaf0e3039a806f29be9d7034d66466a4839a01de0610" +checksum = "ae48fdc7509942ece1e57cec41013571eca8f8114b0378415e51c9d353f750f2" dependencies = [ "bytesize", "kstat-rs", @@ -13652,7 +13652,7 @@ dependencies = [ "levenshtein_automata", "log", "lru 0.18.5", - "lz4_flex 0.14.0", + "lz4_flex 0.14.2", "measure_time", "memmap2", "once_cell", @@ -13722,7 +13722,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d60769b80ad7953d8a7b2c70cdfe722bbcdcac6bccc8ac934c40c034d866fc18" dependencies = [ "byteorder", - "regex-syntax 0.8.11", + "regex-syntax 0.8.12", "utf8-ranges", ] @@ -14728,7 +14728,7 @@ checksum = "0203df02a3b6dd63575cc1d6e609edc2181c9a11867a271b25cfd2abff3ec5ca" dependencies = [ "cc", "regex", - "regex-syntax 0.8.11", + "regex-syntax 0.8.12", "tree-sitter-language", ] @@ -14895,9 +14895,9 @@ dependencies = [ [[package]] name = "ucd-trie" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" +checksum = "8f20bdbfc9915686faa18fb5bbe8b4552778505defbf9f12289beefbc44092a6" [[package]] name = "ulid" @@ -15168,9 +15168,9 @@ checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] name = "uuid" -version = "1.29.2" +version = "1.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" dependencies = [ "getrandom 0.4.3", "js-sys", @@ -15241,7 +15241,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b7d4dba01e366e2ffbdf0700b1876f747c548db72dced534de41c54945c0148" dependencies = [ "libc", - "nix 0.31.3", + "nix 0.31.4", ] [[package]] @@ -15483,9 +15483,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] @@ -15496,14 +15496,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.11", + "webpki-roots 1.0.12", ] [[package]] name = "webpki-roots" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" dependencies = [ "rustls-pki-types", ] @@ -15601,7 +15601,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-nats", @@ -15691,7 +15691,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.866.0" +version = "1.880.1" dependencies = [ "async-stream", "async-trait", @@ -15726,7 +15726,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "chrono", @@ -15739,7 +15739,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "argon2", @@ -15881,7 +15881,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "chrono", @@ -15905,7 +15905,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "chrono", @@ -15922,7 +15922,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "axum", @@ -15948,7 +15948,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.866.0" +version = "1.880.1" dependencies = [ "reqwest 0.12.28", "serde", @@ -15958,7 +15958,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "chrono", @@ -15975,7 +15975,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "base64 0.22.1", @@ -15997,7 +15997,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "axum", @@ -16020,7 +16020,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "chrono", @@ -16036,7 +16036,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "chrono", @@ -16058,7 +16058,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "chrono", @@ -16082,7 +16082,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "chrono", @@ -16096,7 +16096,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-nats", @@ -16132,7 +16132,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "axum", @@ -16158,7 +16158,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "chrono", @@ -16186,7 +16186,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "axum", @@ -16208,7 +16208,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "chrono", @@ -16227,7 +16227,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "axum", @@ -16269,7 +16269,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "axum", @@ -16294,12 +16294,13 @@ dependencies = [ "windmill-api-auth", "windmill-audit", "windmill-common", + "windmill-oauth", "windmill-object-store", ] [[package]] name = "windmill-api-sse" -version = "1.866.0" +version = "1.880.1" dependencies = [ "lazy_static", "serde", @@ -16311,7 +16312,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.866.0" +version = "1.880.1" dependencies = [ "argon2", "axum", @@ -16335,7 +16336,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "chrono", @@ -16350,7 +16351,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.866.0" +version = "1.880.1" dependencies = [ "axum", "chrono", @@ -16389,7 +16390,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.866.0" +version = "1.880.1" dependencies = [ "chrono", "lazy_static", @@ -16404,7 +16405,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "axum", @@ -16423,7 +16424,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.866.0" +version = "1.880.1" dependencies = [ "aes-gcm", "aho-corasick", @@ -16530,7 +16531,7 @@ dependencies = [ "url", "urlencoding", "uuid", - "webpki-roots 1.0.11", + "webpki-roots 1.0.12", "windmill-macros", "windmill-parser", "windmill-parser-py", @@ -16542,7 +16543,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.866.0" +version = "1.880.1" dependencies = [ "chrono", "futures", @@ -16562,7 +16563,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.866.0" +version = "1.880.1" dependencies = [ "regex", "serde", @@ -16579,7 +16580,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16606,7 +16607,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "futures", @@ -16623,7 +16624,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.866.0" +version = "1.880.1" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16639,7 +16640,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -16661,7 +16662,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -16693,7 +16694,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "arc-swap", @@ -16718,7 +16719,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-stream", @@ -16754,7 +16755,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "futures", @@ -16773,7 +16774,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.866.0" +version = "1.880.1" dependencies = [ "convert_case 0.6.0", "serde", @@ -16782,7 +16783,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "lazy_static", @@ -16794,7 +16795,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "serde_json", @@ -16806,7 +16807,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "gosyn", @@ -16818,7 +16819,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "lazy_static", @@ -16830,7 +16831,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "serde_json", @@ -16842,7 +16843,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "nu-parser", @@ -16853,7 +16854,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16864,7 +16865,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16876,7 +16877,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -16887,7 +16888,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-recursion", @@ -16910,7 +16911,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "serde_json", @@ -16922,7 +16923,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "lazy_static", @@ -16936,7 +16937,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16953,7 +16954,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "lazy_static", @@ -16966,7 +16967,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "serde", @@ -16978,7 +16979,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "lazy_static", @@ -16996,7 +16997,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -17012,7 +17013,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -17029,7 +17030,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "lazy_static", @@ -17043,7 +17044,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-recursion", @@ -17081,7 +17082,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "const_format", @@ -17119,7 +17120,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.866.0" +version = "1.880.1" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17130,7 +17131,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-recursion", @@ -17165,7 +17166,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -17189,7 +17190,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -17222,7 +17223,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -17249,7 +17250,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -17282,7 +17283,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -17302,7 +17303,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -17336,7 +17337,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -17373,7 +17374,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -17396,7 +17397,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -17420,7 +17421,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-nats", @@ -17444,7 +17445,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -17479,7 +17480,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -17507,7 +17508,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-trait", @@ -17533,7 +17534,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17543,6 +17544,7 @@ dependencies = [ "rand 0.9.5", "serde", "serde_json", + "serde_yml", "sqlx", "strum", "tracing", @@ -17552,7 +17554,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-once-cell", @@ -17670,9 +17672,10 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.866.0" +version = "1.880.1" dependencies = [ "bytes", + "fs4", "futures", "lazy_static", "md-5 0.10.6", @@ -18508,9 +18511,9 @@ dependencies = [ [[package]] name = "zeroize" -version = "1.9.1" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" dependencies = [ "zeroize_derive", ] @@ -18600,27 +18603,27 @@ dependencies = [ [[package]] name = "zstd" -version = "0.13.4" +version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb02c3132d251ab1606e9fc913a7da6c6ed08cc263df15edf082e1dc497d157" +checksum = "50adf04cf3ec914b0b9905c9dde90c80fe74bfd701e331fc80a39c512c525278" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "7.4.0" +version = "7.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c8ea04668f5de8d8d51051714ba560c9536519cadcdb8829bba4fe2ad159b03" +checksum = "498d94ad68720c89b4fbe41b9090850651e68cb2dd9210ce7ffbff3a94653819" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.1.2+zstd.1.5.7" +version = "2.1.3+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +checksum = "f729a06d0257428fd9d997ac8db7e1407bd0262ab016b085b36bc52957c0052d" dependencies = [ "cc", "pkg-config", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 6b84a24949..227996c52a 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.866.0" +version = "1.880.1" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.866.0" +version = "1.880.1" authors = ["Ruben Fiszel "] edition = "2021" diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 7fe20e438b..40a56983ff 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -d7d509d0955c52f83afd0bf8b61a0e811162c16f +cac1d382a7c22e8a4e9c56832ad12d11de5bba7f diff --git a/backend/migrations/20261016171440_ai_agent_checkpoint_waiting_on.down.sql b/backend/migrations/20261016171440_ai_agent_checkpoint_waiting_on.down.sql new file mode 100644 index 0000000000..0be0740817 --- /dev/null +++ b/backend/migrations/20261016171440_ai_agent_checkpoint_waiting_on.down.sql @@ -0,0 +1 @@ +ALTER TABLE ai_agent_checkpoint DROP COLUMN IF EXISTS waiting_on; diff --git a/backend/migrations/20261016171440_ai_agent_checkpoint_waiting_on.up.sql b/backend/migrations/20261016171440_ai_agent_checkpoint_waiting_on.up.sql new file mode 100644 index 0000000000..f0f86bf777 --- /dev/null +++ b/backend/migrations/20261016171440_ai_agent_checkpoint_waiting_on.up.sql @@ -0,0 +1,3 @@ +-- The background tool jobs a parked AI agent waits on: the monitor wakes it once one of them has +-- completed. Empty while it waits on an approval, whose answer comes first. +ALTER TABLE ai_agent_checkpoint ADD COLUMN IF NOT EXISTS waiting_on UUID[] NOT NULL DEFAULT '{}'; diff --git a/backend/migrations/20261109144118_ai_memory_turn.down.sql b/backend/migrations/20261109144118_ai_memory_turn.down.sql new file mode 100644 index 0000000000..98ca560af1 --- /dev/null +++ b/backend/migrations/20261109144118_ai_memory_turn.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS ai_memory_turn; diff --git a/backend/migrations/20261109144118_ai_memory_turn.up.sql b/backend/migrations/20261109144118_ai_memory_turn.up.sql new file mode 100644 index 0000000000..d1582e2cf1 --- /dev/null +++ b/backend/migrations/20261109144118_ai_memory_turn.up.sql @@ -0,0 +1,12 @@ +-- The run that holds each memory id: a run started with a memory id is refused while the one +-- holding it is still queued. A row whose job left the queue is free to take over, and the +-- monitor deletes it. No foreign key to v2_job_queue: one would lock that table on every push. +CREATE TABLE IF NOT EXISTS ai_memory_turn ( + workspace_id VARCHAR(50) NOT NULL, + memory_id UUID NOT NULL, + job_id UUID NOT NULL, + -- Background jobs of a parked turn this run took over, by flow step id: that step's agent + -- adopts them when it starts. + handed_jobs JSONB, + PRIMARY KEY (workspace_id, memory_id) +); diff --git a/backend/migrations/20261111135920_git_sync_pr_check_head.down.sql b/backend/migrations/20261111135920_git_sync_pr_check_head.down.sql new file mode 100644 index 0000000000..bbcdecdb11 --- /dev/null +++ b/backend/migrations/20261111135920_git_sync_pr_check_head.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS git_sync_pr_check_head; diff --git a/backend/migrations/20261111135920_git_sync_pr_check_head.up.sql b/backend/migrations/20261111135920_git_sync_pr_check_head.up.sql new file mode 100644 index 0000000000..8fcf90c36a --- /dev/null +++ b/backend/migrations/20261111135920_git_sync_pr_check_head.up.sql @@ -0,0 +1,17 @@ +-- The last pull/merge request head the "Windmill diff" check ran for, per git-sync +-- repository. The webhook receiver and the auto-pull poller both claim a head here +-- before checking it, so each head is checked once whichever path sees it first. +CREATE TABLE git_sync_pr_check_head ( + workspace_id VARCHAR(50) NOT NULL REFERENCES workspace(id) ON DELETE CASCADE, + repo_resource_path VARCHAR(255) NOT NULL, + pr_number BIGINT NOT NULL, + head_sha VARCHAR(64) NOT NULL, + checked_at TIMESTAMPTZ NOT NULL DEFAULT now(), + -- Whether the check was started. A claim whose check never started (an error, + -- or a restart in between) may be claimed again after a delay. + started BOOLEAN NOT NULL DEFAULT false, + PRIMARY KEY (workspace_id, repo_resource_path, pr_number) +); + +GRANT ALL ON git_sync_pr_check_head TO windmill_user; +GRANT ALL ON git_sync_pr_check_head TO windmill_admin; diff --git a/backend/migrations/20261112005655_kafka_pending_commits_follow_trigger_path.down.sql b/backend/migrations/20261112005655_kafka_pending_commits_follow_trigger_path.down.sql new file mode 100644 index 0000000000..dd11a125df --- /dev/null +++ b/backend/migrations/20261112005655_kafka_pending_commits_follow_trigger_path.down.sql @@ -0,0 +1,5 @@ +ALTER TABLE kafka_pending_commits + DROP CONSTRAINT kafka_pending_commits_workspace_id_kafka_trigger_path_fkey, + ADD CONSTRAINT kafka_pending_commits_workspace_id_kafka_trigger_path_fkey + FOREIGN KEY (workspace_id, kafka_trigger_path) REFERENCES kafka_trigger(workspace_id, path) + ON DELETE CASCADE; diff --git a/backend/migrations/20261112005655_kafka_pending_commits_follow_trigger_path.up.sql b/backend/migrations/20261112005655_kafka_pending_commits_follow_trigger_path.up.sql new file mode 100644 index 0000000000..17552aefd0 --- /dev/null +++ b/backend/migrations/20261112005655_kafka_pending_commits_follow_trigger_path.up.sql @@ -0,0 +1,7 @@ +-- A trigger's path moves on rename, user rename and offboarding; its pending commits must follow +-- it, or the move fails while any are queued. +ALTER TABLE kafka_pending_commits + DROP CONSTRAINT kafka_pending_commits_workspace_id_kafka_trigger_path_fkey, + ADD CONSTRAINT kafka_pending_commits_workspace_id_kafka_trigger_path_fkey + FOREIGN KEY (workspace_id, kafka_trigger_path) REFERENCES kafka_trigger(workspace_id, path) + ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/backend/migrations/20261112200337_volume_generation.down.sql b/backend/migrations/20261112200337_volume_generation.down.sql new file mode 100644 index 0000000000..30b378e5c7 --- /dev/null +++ b/backend/migrations/20261112200337_volume_generation.down.sql @@ -0,0 +1 @@ +ALTER TABLE volume DROP COLUMN IF EXISTS generation; diff --git a/backend/migrations/20261112200337_volume_generation.up.sql b/backend/migrations/20261112200337_volume_generation.up.sql new file mode 100644 index 0000000000..4616bcb336 --- /dev/null +++ b/backend/migrations/20261112200337_volume_generation.up.sql @@ -0,0 +1,3 @@ +-- Odd while a writer is changing the volume's objects, even otherwise. Read-only mounts take no +-- lease and use it to detect a write that overlapped their pull. +ALTER TABLE volume ADD COLUMN IF NOT EXISTS generation BIGINT NOT NULL DEFAULT 0; diff --git a/backend/migrations/20261113164906_raw_app_policy_static_input_references.down.sql b/backend/migrations/20261113164906_raw_app_policy_static_input_references.down.sql new file mode 100644 index 0000000000..fc57e987e7 --- /dev/null +++ b/backend/migrations/20261113164906_raw_app_policy_static_input_references.down.sql @@ -0,0 +1 @@ +-- Nothing to undo: the up migration only stores values the app itself states. diff --git a/backend/migrations/20261113164906_raw_app_policy_static_input_references.up.sql b/backend/migrations/20261113164906_raw_app_policy_static_input_references.up.sql new file mode 100644 index 0000000000..dfd261ec97 --- /dev/null +++ b/backend/migrations/20261113164906_raw_app_policy_static_input_references.up.sql @@ -0,0 +1,43 @@ +-- Store static input references in raw-app policies: where the latest version of a raw app gives a +-- static input as a `$var:`, `$jsonvar:` or `$res:` reference, its policy holds that reference. +DO $mig$ +DECLARE + r record; +BEGIN + FOR r IN + WITH latest AS MATERIALIZED ( + -- Read with its NUL escapes removed, as `strip_json_nul` does, since jsonb refuses them: + -- backslash pairs are set aside first, so a `\u0000` after an escaped backslash stays. + -- chr(1) cannot occur in json text, which keeps control characters escaped. + SELECT a.id, a.policy, + replace(replace(replace(v.value::text, chr(92) || chr(92), chr(1)), chr(92) || 'u0000', ''), + chr(1), chr(92) || chr(92))::jsonb AS value + FROM app a + JOIN app_version v ON v.id = a.versions[array_upper(a.versions, 1)] + WHERE v.raw_app + AND v.value::text ~ '"\$(var|jsonvar|res):' + ) + SELECT l.id, t.key AS triggerable, f.key AS field, rf.value->'value' AS reference + FROM latest l + CROSS JOIN LATERAL jsonb_each(CASE jsonb_typeof(l.value->'runnables') WHEN 'object' THEN l.value->'runnables' END) rn + CROSS JOIN LATERAL jsonb_each(CASE jsonb_typeof(rn.value->'fields') WHEN 'object' THEN rn.value->'fields' END) rf + CROSS JOIN LATERAL jsonb_each(CASE jsonb_typeof(l.policy->'triggerables_v2') WHEN 'object' THEN l.policy->'triggerables_v2' END) t + CROSS JOIN LATERAL jsonb_each(CASE jsonb_typeof(t.value->'static_inputs') WHEN 'object' THEN t.value->'static_inputs' END) f + -- A key is `:/`. Ids may hold `:`, hashes and paths never + -- do, so the id is exactly what precedes the last `:`. + WHERE rn.key = left(t.key, length(t.key) - strpos(reverse(t.key), ':')) + AND substr(t.key, length(rn.key) + 2) ~ '^(rawscript|script|flow|agent)/' + AND f.key = rf.key + AND rf.value->>'type' = 'static' + AND rf.value->>'value' ~ '^\$(var|jsonvar|res):' + AND f.value IS DISTINCT FROM rf.value->'value' + LOOP + UPDATE app + SET policy = jsonb_set(policy, ARRAY['triggerables_v2', r.triggerable, 'static_inputs', r.field], r.reference) + WHERE id = r.id; + END LOOP; +-- Never blocks startup: an error undoes this block's changes and is logged instead. +EXCEPTION WHEN OTHERS THEN + RAISE WARNING 'raw_app_policy_static_input_references: % (%), no policy changed', SQLERRM, SQLSTATE; +END +$mig$; diff --git a/backend/migrations/20261117111023_ai_shared_session_opened.down.sql b/backend/migrations/20261117111023_ai_shared_session_opened.down.sql new file mode 100644 index 0000000000..4d72edec92 --- /dev/null +++ b/backend/migrations/20261117111023_ai_shared_session_opened.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS ai_shared_session_opened; diff --git a/backend/migrations/20261117111023_ai_shared_session_opened.up.sql b/backend/migrations/20261117111023_ai_shared_session_opened.up.sql new file mode 100644 index 0000000000..b841c7011d --- /dev/null +++ b/backend/migrations/20261117111023_ai_shared_session_opened.up.sql @@ -0,0 +1,17 @@ +-- The shares a member opened by link, which is what lists them in that member's sidebar. +-- Removing one from the list deletes its row; opening the link again brings it back. +CREATE TABLE ai_shared_session_opened ( + share_id UUID NOT NULL REFERENCES ai_shared_session(id) ON DELETE CASCADE, + email VARCHAR(255) NOT NULL, + opened_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (share_id, email) +); + +GRANT ALL ON ai_shared_session_opened TO windmill_admin; +GRANT ALL ON ai_shared_session_opened TO windmill_user; + +-- The handlers go through the raw pool and scope every query themselves; this is the backstop +-- for a future query that reaches the table through UserDB. +ALTER TABLE ai_shared_session_opened ENABLE ROW LEVEL SECURITY; + +CREATE POLICY admin_policy ON ai_shared_session_opened FOR ALL TO windmill_admin USING (true); diff --git a/backend/migrations/20261118160046_github_app_repo_approval.down.sql b/backend/migrations/20261118160046_github_app_repo_approval.down.sql new file mode 100644 index 0000000000..13a4c08fb2 --- /dev/null +++ b/backend/migrations/20261118160046_github_app_repo_approval.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS github_app_repo_approval; diff --git a/backend/migrations/20261118160046_github_app_repo_approval.up.sql b/backend/migrations/20261118160046_github_app_repo_approval.up.sql new file mode 100644 index 0000000000..3c14bf0aa2 --- /dev/null +++ b/backend/migrations/20261118160046_github_app_repo_approval.up.sql @@ -0,0 +1,16 @@ +-- The repository URL a workspace admin last saved on an app-backed git_repository +-- resource. Anyone who can write the resource controls its URL, so the GitHub App +-- installation serves a non-admin only the repository this names. The cascading FK +-- carries it through every rename and takes it with a delete, so a new resource at +-- a freed path never inherits an approval. +CREATE TABLE github_app_repo_approval ( + workspace_id VARCHAR(50) NOT NULL, + path VARCHAR(255) NOT NULL, + url TEXT NOT NULL, + PRIMARY KEY (workspace_id, path), + FOREIGN KEY (workspace_id, path) REFERENCES resource (workspace_id, path) + ON DELETE CASCADE ON UPDATE CASCADE +); + +GRANT ALL ON github_app_repo_approval TO windmill_user; +GRANT ALL ON github_app_repo_approval TO windmill_admin; diff --git a/backend/migrations/20261119133214_autoscaling_decision.down.sql b/backend/migrations/20261119133214_autoscaling_decision.down.sql new file mode 100644 index 0000000000..0187bd4a47 --- /dev/null +++ b/backend/migrations/20261119133214_autoscaling_decision.down.sql @@ -0,0 +1,2 @@ +DROP TABLE IF EXISTS autoscaling_decision; +DROP TABLE IF EXISTS autoscaling_recording; diff --git a/backend/migrations/20261119133214_autoscaling_decision.up.sql b/backend/migrations/20261119133214_autoscaling_decision.up.sql new file mode 100644 index 0000000000..d86941920e --- /dev/null +++ b/backend/migrations/20261119133214_autoscaling_decision.up.sql @@ -0,0 +1,22 @@ +-- Worker groups whose autoscaling decisions are being recorded, until `until`. +CREATE TABLE IF NOT EXISTS autoscaling_recording ( + worker_group TEXT PRIMARY KEY, + until TIMESTAMPTZ NOT NULL, + started_by TEXT NOT NULL +); + +-- One row per autoscaling tick of a recorded worker group: what it saw and what it decided. +CREATE TABLE IF NOT EXISTS autoscaling_decision ( + id BIGSERIAL PRIMARY KEY, + worker_group TEXT NOT NULL, + recorded_at TIMESTAMPTZ NOT NULL DEFAULT now(), + worker_count INTEGER NOT NULL, + occupancy_rate_15s REAL, + occupancy_rate_5m REAL, + occupancy_rate_30m REAL, + jobs_waiting JSONB NOT NULL, + decision TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS autoscaling_decision_worker_group_idx + ON autoscaling_decision (worker_group, recorded_at); diff --git a/backend/parsers/windmill-parser-csharp/src/lib.rs b/backend/parsers/windmill-parser-csharp/src/lib.rs index 2c068f0901..f39aac738a 100644 --- a/backend/parsers/windmill-parser-csharp/src/lib.rs +++ b/backend/parsers/windmill-parser-csharp/src/lib.rs @@ -69,15 +69,26 @@ pub fn parse_csharp_sig_meta(code: &str) -> anyhow::Result { for p_list_node in param_list.children(&mut param_list.walk()) { if p_list_node.kind() == "parameter" { let mut default = None; + let mut has_default = false; for a in p_list_node.children(&mut p_list_node.walk()) { if a.kind() == "=" { if let Some(node) = a.next_sibling() { + // Optional even when the default (1.5f, 'x', a const) is not JSON. + has_default = true; default = csharp_param_default_value(node, code); } } } let (otyp, typ, name) = parse_csharp_typ(p_list_node, code)?; - args.push(Arg { name, otyp, typ, default, has_default: false, oidx: None, otyp_inferred: false }); + args.push(Arg { + name, + otyp, + typ, + default, + has_default, + oidx: None, + otyp_inferred: false, + }); } } } @@ -279,14 +290,47 @@ class LilProgram assert_eq!(ret.args[0].name, "myString"); assert_eq!(ret.args[0].otyp, Some("string".to_string())); assert_eq!(ret.args[0].typ, Typ::Str(None)); + assert_eq!(ret.args[0].default, Some(serde_json::json!("World"))); + assert_eq!(ret.args[0].has_default, true); assert_eq!(ret.args[1].name, "myInt"); assert_eq!(ret.args[1].otyp, Some("int".to_string())); assert_eq!(ret.args[1].typ, Typ::Int); + assert_eq!(ret.args[1].default, None); + assert_eq!(ret.args[1].has_default, false); assert_eq!(ret.args[2].name, "jj"); assert_eq!(ret.args[2].otyp, Some("string[]".to_string())); assert_eq!(ret.args[2].typ, Typ::List(Box::new(Typ::Str(None)))); + assert_eq!(ret.args[2].default, None); + assert_eq!(ret.args[2].has_default, false); + } + + #[test] + fn a_default_that_is_not_json_still_makes_the_argument_optional() { + let code = r#" +class Script +{ + const int Answer = 42; + public static string Main(double ratio = 1.5f, char c = 'x', int n = Answer, int required) + { + return ""; + } +}"#; + let args = parse_csharp_signature(code).unwrap().args; + let summary: Vec<_> = args + .iter() + .map(|a| (a.name.as_str(), a.has_default, a.default.clone())) + .collect(); + assert_eq!( + summary, + vec![ + ("ratio", true, None), + ("c", true, None), + ("n", true, None), + ("required", false, None), + ] + ); } #[test] diff --git a/backend/parsers/windmill-parser-py/src/lib.rs b/backend/parsers/windmill-parser-py/src/lib.rs index 5a9eabc33e..b9edcb111a 100644 --- a/backend/parsers/windmill-parser-py/src/lib.rs +++ b/backend/parsers/windmill-parser-py/src/lib.rs @@ -168,7 +168,10 @@ fn filter_relevant_statements(code: &str) -> String { while let Some(line) = lines.next() { let trimmed = line.trim_start(); - if trimmed.starts_with("class ") || trimmed.starts_with("def ") { + if trimmed.starts_with("class ") + || trimmed.starts_with("def ") + || trimmed.starts_with("async def ") + { result.push(line); let base_indent = line.len() - trimmed.len(); @@ -203,7 +206,9 @@ fn extract_code_metadata(code: &str, main_name: &str) -> CodeMetadata { let filtered_code = filter_relevant_statements(code); - let ast = match parse_module(&filtered_code) { + // The line-based prefilter cuts a block at a column-0 line inside a multiline + // string (e.g. SQL in a triple-quoted literal), so fall back to the full source. + let ast = match parse_module(&filtered_code).or_else(|_| parse_module(code)) { Ok(parsed) => parsed.into_suite(), Err(_) => return CodeMetadata { enums, descriptions }, }; @@ -243,14 +248,12 @@ fn extract_code_metadata(code: &str, main_name: &str) -> CodeMetadata { } } } - 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::StringLiteral(docstring) = expr_stmt.value.as_ref() { - descriptions = parse_docstring_args(docstring.value.to_str()); - } + Stmt::FunctionDef(StmtFunctionDef { name: func_name, body, .. }) + if has_docstring && func_name.as_str() == main_name => + { + if let Some(Stmt::Expr(expr_stmt)) = body.first() { + if let Expr::StringLiteral(docstring) = expr_stmt.value.as_ref() { + descriptions = parse_docstring_args(docstring.value.to_str()); } } } @@ -1426,4 +1429,33 @@ def main(p: Point, name: str = "world"): } Ok(()) } + + #[test] + fn test_parse_python_sig_async_main_docstring_args() -> anyhow::Result<()> { + let code = r#" +from enum import Enum + +class Color(str, Enum): + RED = 'red' + GREEN = 'green' + +async def main(color: Color = Color.RED): + """ + Args: + color: Color to use + """ + query = """ +SELECT 1 +""" + return query +"#; + let result = parse_python_signature(code, None, false)?; + assert_eq!(result.args[0].otyp, Some("Color to use".to_string())); + assert_eq!( + result.args[0].typ, + Typ::Str(Some(vec!["red".to_string(), "green".to_string()])) + ); + assert_eq!(result.args[0].default, Some(json!("red"))); + Ok(()) + } } diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index b62513aef0..c3ba920091 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.866.0" +version = "1.880.1" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.866.0" +version = "1.880.1" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.866.0" +version = "1.880.1" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.866.0" +version = "1.880.1" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index 750721fa8c..71531bc1aa 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.866.0" +version = "1.880.1" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/src/main.rs b/backend/src/main.rs index 8d42a8e031..fcb4ac412d 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -689,6 +689,18 @@ async fn windmill_main() -> anyhow::Result<()> { _ => {} } + // A worker that kept the variable would otherwise silently serve every workspace, the + // overloaded one included. + if std::env::var("WORKSPACE_FAIRNESS_RESERVE_WORKER") + .is_ok_and(|x| x == "1" || x.eq_ignore_ascii_case("true")) + { + eprintln!( + "WORKSPACE_FAIRNESS_RESERVE_WORKER is no longer read: unset it and enable \"Fairness \ + reserve\" (fairness_reserve) in the worker group config instead" + ); + std::process::exit(1); + } + // 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 { diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index 57b96db902..5f7273d090 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -361,7 +361,7 @@ pub async fn initial_load( } }); - // Workspace fairness (cloud-only). The percentage/duration/min knobs apply + // Workspace fairness (Enterprise). The percentage/duration/min knobs apply // *before* the enabled flag so that `apply_workspace_fairness_enabled` reads // current values when re-storing the pull queries, which declaration order gives us. pass.setting( @@ -465,6 +465,8 @@ pub async fn initial_load( object_store_cache_config: None, // nor whether it is paused: the server refuses it jobs instead paused: false, + // the server pulls for it with its own query, which the reserve gate never sees + fairness_reserve: false, })); } } @@ -982,6 +984,11 @@ pub async fn apply_workspace_fairness_enabled(value: Option) _ => false, }; let prev = WORKSPACE_FAIRNESS_ENABLED.swap(new_enabled, Ordering::Relaxed); + if !new_enabled && WORKER_CONFIG.load().fairness_reserve { + tracing::warn!( + "fairness reserve worker stays idle: {WORKSPACE_FAIRNESS_ENABLED_SETTING} is off" + ); + } // Re-store the pull queries so the fairness variants appear/disappear in // lockstep with the toggle. if prev != new_enabled { @@ -2144,6 +2151,20 @@ pub async fn delete_expired_items(db: &DB) -> () { tracing::error!("Error deleting autoscaling event on CE: {:?}", e); } + // A recording lasts at most a day (`AUTOSCALING_RECORDING_SECS`), so its decisions are + // still there for a day after it ends. + if let Err(e) = sqlx::query!( + "WITH decisions AS ( + DELETE FROM autoscaling_decision WHERE recorded_at <= now() - interval '48 hours' + ) + DELETE FROM autoscaling_recording WHERE until <= now()" + ) + .execute(db) + .await + { + tracing::error!("Error deleting autoscaling decisions: {:?}", e); + } + // native_retry_attempt has no FK to v2_job (kept off the hot bulk delete). // Retention sweeps markers alongside the jobs it deletes, but direct job // deletions (workspace/job/schedule clearing) leave markers orphaned — reap @@ -3378,8 +3399,7 @@ pub async fn reload_sandbox_image_default_registry_setting(conn: &Connection) { pub async fn reload_sandbox_registry_auth_setting(conn: &Connection) { // Secret-aware: the value is a raw docker/podman auth.json with credentials, so - // it must never be logged. Load directly (the generic reload_option_setting path - // logs the value via load_option_setting_value) and only log a redacted message. + // it must never be logged. Load directly and only log a redacted message. match load_value_from_global_settings_with_conn(conn, SANDBOX_REGISTRY_AUTH_SETTING, true).await { Ok(q) => apply_sandbox_registry_auth_setting(q).await, @@ -3448,7 +3468,10 @@ async fn resolve_license_key_value(conn: &Connection, quiet: bool) -> anyhow::Re } value = v; } else { - tracing::error!("Could not parse LICENSE_KEY found: {:#?}", &q); + tracing::error!( + "Could not parse LICENSE_KEY found: {}", + loggable_setting_value(&q) + ); } }; Ok(value) @@ -3900,6 +3923,20 @@ pub async fn load_option_setting_value( Ok(parse_option_setting_value(q, setting_name, std_env_var)) } +/// What a settings loader may print of a value. Credentials (registry tokens, `.npmrc`, index +/// URLs with basic auth, `settings.xml`, PATs) all live in string or object settings, so only +/// scalars are printed: a deny-list of secret setting names would leak each new one added. +fn loggable_setting_value(v: &serde_json::Value) -> String { + match v { + serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => { + v.to_string() + } + serde_json::Value::String(s) => format!("", s.len()), + serde_json::Value::Array(a) => format!("", a.len()), + serde_json::Value::Object(o) => format!("", o.len()), + } +} + /// The half of [`load_option_setting_value`] after the read, so [`SettingsPass`] can parse a /// value it already fetched. pub fn parse_option_setting_value( @@ -3920,10 +3957,16 @@ pub fn parse_option_setting_value( if let Some(q) = q { if let Ok(v) = serde_json::from_value::(q.clone()) { - tracing::info!("Loaded setting {setting_name} from db config: {:#?}", &q); + tracing::info!( + "Loaded setting {setting_name} from db config: {}", + loggable_setting_value(&q) + ); value = Some(v) } else { - tracing::error!("Could not parse {setting_name} found: {:#?}", &q); + tracing::error!( + "Could not parse {setting_name} found: {}", + loggable_setting_value(&q) + ); } }; @@ -4046,7 +4089,10 @@ pub fn parse_url_list_setting_value( ); value = if urls.is_empty() { None } else { Some(urls) }; } else { - tracing::error!("Could not parse {} found: {:#?}", setting_name, &q); + tracing::error!( + "Could not parse {setting_name} found: {}", + loggable_setting_value(&q) + ); } } @@ -4107,10 +4153,16 @@ pub fn parse_setting_value( if let Some(q) = q { if let Ok(v) = serde_json::from_value::(q.clone()) { - tracing::info!("Loaded setting {setting_name} from db config: {:#?}", &q); + tracing::info!( + "Loaded setting {setting_name} from db config: {}", + loggable_setting_value(&q) + ); value = transformer(v); } else { - tracing::error!("Could not parse {setting_name} found: {:#?}", &q); + tracing::error!( + "Could not parse {setting_name} found: {}", + loggable_setting_value(&q) + ); } }; @@ -4261,8 +4313,11 @@ pub async fn monitor_db( if let Err(e) = cleanup_flow_iterator_data_orphaned_jobs(&db).await { tracing::error!("Error cleaning up flow_iterator_data: {:?}", e); } - if let Err(e) = cleanup_ai_agent_checkpoint_orphaned_jobs(&db).await { - tracing::error!("Error cleaning up ai_agent_checkpoint: {:?}", e); + if let Err(e) = cleanup_ai_agent_orphaned_rows(&db).await { + tracing::error!( + "Error cleaning up AI agent checkpoints and memory claims: {:?}", + e + ); } } } @@ -4578,6 +4633,17 @@ pub async fn monitor_db( } }; + // Every pass: a parked AI agent waits on this for its background tool jobs. + let wake_ai_agents_f = async { + if server_mode && !initial_load { + if let Some(db) = conn.as_sql() { + if let Err(e) = wake_ai_agents_with_finished_background_jobs(&db).await { + tracing::error!("Error waking AI agents on background jobs: {:?}", e); + } + } + } + }; + // run every 30 iterations (~5min at the default LISTEN_NEW_EVENTS_INTERVAL_SEC). let stranded_jobs_f = async { if server_mode && iteration.is_some() && iteration.as_ref().unwrap().should_run(30) { @@ -4732,6 +4798,7 @@ pub async fn monitor_db( pipeline_freshness_watchdog_f, reconcile_unarmed_schedules_f, stranded_jobs_f, + wake_ai_agents_f, ); } @@ -5277,6 +5344,7 @@ async fn poll_git_auto_pull_inner(db: &Pool) -> error::Result<()> { db, &row.workspace_id, &repo.git_repo_resource_path, + windmill_common::ssrf::GitRemoteCaller::AdminOrSystem, ) .await } @@ -5325,6 +5393,26 @@ async fn poll_git_auto_pull_inner(db: &Pool) -> error::Result<()> { ) .await; } + + // The pull request "Windmill diff" check, for heads no webhook + // delivery has checked (an instance the host cannot reach). + #[cfg(feature = "enterprise")] + if git_ref != "HEAD" { + if let Err(e) = windmill_api::git_sync_ee::poll_pr_diff_checks( + db, + &row.workspace_id, + repo, + &git_ref, + ) + .await + { + tracing::warn!( + "git auto-pull: PR diff check poll failed for {}/{}: {e:#}", + row.workspace_id, + repo.git_repo_resource_path + ); + } + } } Ok(None) => {} Err(e) => { @@ -5913,14 +6001,16 @@ pub async fn reload_worker_config(db: &DB, tx: KillpillSender, kill_if_change: b .as_ref() .is_some_and(|dws| !dws.is_empty()); - // Pausing or resuming must not restart the workers, dedicated ones included: a reload - // whose only difference is the flag skips every restart below. + // Pausing or resuming, or flagging the group as a fairness reserve, must not restart the + // workers, dedicated ones included: a reload whose only difference is a flag skips every + // restart below. // Tags only decide what the workers pull, and the pull query is swapped below: a change // to them alone needs no restart either. A script toggled under a `dedicated_workers` // pattern comes in this way, its dependency job tagged for the group before it has a lock. let only_live_fields_changed = **wc != config && WorkerConfig { paused: wc.paused, + fairness_reserve: wc.fairness_reserve, worker_tags: wc.worker_tags.clone(), priority_tags_sorted: wc.priority_tags_sorted.clone(), ..config.clone() @@ -5934,7 +6024,11 @@ pub async fn reload_worker_config(db: &DB, tx: KillpillSender, kill_if_change: b let restart_in_turn = has_dedicated && **wc != config && wc.cache_clear == config.cache_clear; let (deferred, _deferred_rx) = KillpillSender::new(1); - let kill = if restart_in_turn { deferred } else { tx.clone() }; + let kill = if restart_in_turn { + deferred + } else { + tx.clone() + }; if wc.dedicated_worker != config.dedicated_worker || wc.dedicated_workers != config.dedicated_workers || (has_dedicated && **wc != config) @@ -5977,9 +6071,30 @@ pub async fn reload_worker_config(db: &DB, tx: KillpillSender, kill_if_change: b } if restart_in_turn { - windmill_common::worker::restart_dedicated_worker_in_turn(db.clone(), tx.clone()); + windmill_common::worker::restart_dedicated_worker_in_turn( + db.clone(), + tx.clone(), + ); } } + if config.fairness_reserve + && !wc.fairness_reserve + && !WORKSPACE_FAIRNESS_ENABLED.load(Ordering::Relaxed) + { + tracing::warn!( + "fairness reserve worker stays idle: {WORKSPACE_FAIRNESS_ENABLED_SETTING} is off" + ); + } + if wc.fairness_reserve != config.fairness_reserve { + tracing::info!( + "fairness reserve {}", + if config.fairness_reserve { + "enabled" + } else { + "disabled" + } + ); + } drop(wc); tracing::info!("Reloading worker config..."); @@ -6078,14 +6193,25 @@ pub async fn apply_base_url_setting( #[cfg(feature = "oauth2")] let oauths = if conn.as_sql().is_some() { if let Some(q) = q_oauth { - if let Ok(v) = serde_json::from_value::< - Option>, - >(q.clone()) - { - v - } else { - tracing::error!("Could not parse oauth setting as a json, found: {:#?}", &q); - None + // Entry by entry, so that one entry that does not parse drops only itself. + match serde_json::from_value::>>(q) { + Ok(v) => v.map(|entries| { + entries + .into_iter() + .filter_map(|(name, raw)| { + serde_json::from_value::(raw) + .map_err(|e| { + tracing::error!("Skipping invalid OAuth client {name}: {e}") + }) + .ok() + .map(|c| (name, c)) + }) + .collect() + }), + Err(e) => { + tracing::error!("Could not parse oauth setting as a json object: {e}"); + None + } } } else { None @@ -7843,10 +7969,30 @@ async fn cleanup_job_result_stream_orphaned_jobs(db: &DB) -> error::Result<()> { Ok(()) } +/// Zero the `suspend` of each parked AI agent with a completed job in its `waiting_on`, so the +/// suspended pull takes it back. Each job is listed by one park only, and an agent no longer +/// parked (`suspend_until` cleared by its pull) is left alone. +async fn wake_ai_agents_with_finished_background_jobs(db: &DB) -> error::Result<()> { + let woken = sqlx::query!( + "UPDATE v2_job_queue q SET suspend = 0 + FROM ai_agent_checkpoint c + WHERE c.waiting_on <> '{}' AND q.id = c.job_id + AND q.suspend > 0 AND q.suspend_until IS NOT NULL + AND EXISTS (SELECT 1 FROM v2_job_completed jc WHERE jc.id = ANY(c.waiting_on))", + ) + .execute(db) + .await? + .rows_affected(); + if woken > 0 { + tracing::info!("Woke {woken} AI agents whose background tool jobs finished"); + } + Ok(()) +} + /// A parked agent cancelled from outside, or a worker that died mid-segment, never deletes its /// checkpoint itself. -async fn cleanup_ai_agent_checkpoint_orphaned_jobs(db: &DB) -> error::Result<()> { - let deleted = sqlx::query( +async fn cleanup_ai_agent_orphaned_rows(db: &DB) -> error::Result<()> { + let deleted = sqlx::query!( "DELETE FROM ai_agent_checkpoint c WHERE NOT EXISTS (SELECT 1 FROM v2_job_queue q WHERE q.id = c.job_id)", ) @@ -7856,6 +8002,38 @@ async fn cleanup_ai_agent_checkpoint_orphaned_jobs(db: &DB) -> error::Result<()> if deleted > 0 { tracing::info!("Cleaned up {deleted} orphaned ai_agent_checkpoint rows"); } + // A memory id's claim is free once its run left the queue; deleting it only keeps the table + // to the memory ids in use. + // Matched on the job too: a claim taken over while this waits on its row lock no longer + // names that job when the delete re-reads it, so it is kept. + // Background jobs handed to a run that ended before its agent adopted them (stopped while an + // earlier step ran, say) are cancelled with it. + let mut tx = db.begin().await?; + let released = sqlx::query_scalar!( + "DELETE FROM ai_memory_turn t + USING (SELECT workspace_id, memory_id, job_id FROM ai_memory_turn s + WHERE NOT EXISTS (SELECT 1 FROM v2_job_queue q WHERE q.id = s.job_id)) stale + WHERE t.workspace_id = stale.workspace_id AND t.memory_id = stale.memory_id + AND t.job_id = stale.job_id + RETURNING t.handed_jobs", + ) + .fetch_all(&mut *tx) + .await?; + let mut cancelled = 0; + for handed_jobs in released.iter().flatten() { + cancelled += windmill_common::flow_conversations::cancel_unadopted_handed_jobs( + &mut *tx, + handed_jobs, + ) + .await?; + } + tx.commit().await?; + if !released.is_empty() { + tracing::info!( + "Cleaned up {} released ai_memory_turn rows, cancelling {cancelled} background jobs no turn adopted", + released.len() + ); + } Ok(()) } @@ -8358,3 +8536,25 @@ mod canceled_zombie_flow_tests { Ok(()) } } + +#[cfg(test)] +mod loggable_setting_value_tests { + use super::loggable_setting_value; + use serde_json::json; + + #[test] + fn never_prints_string_or_structured_values() { + let token = "ghp_secret_token"; + for v in [ + json!(format!( + "[install.scopes]\n\"@org\" = {{ token = \"{token}\" }}" + )), + json!({ "registry": { "token": token } }), + json!([token]), + ] { + assert!(!loggable_setting_value(&v).contains(token)); + } + assert_eq!(loggable_setting_value(&json!(3600)), "3600"); + assert_eq!(loggable_setting_value(&json!(true)), "true"); + } +} diff --git a/backend/summarized_schema.txt b/backend/summarized_schema.txt index 00c46ecac2..a560f7cbae 100644 --- a/backend/summarized_schema.txt +++ b/backend/summarized_schema.txt @@ -37,10 +37,11 @@ _sqlx_migrations: version(bigint), description(text), installed_on(ts), success( account: workspace_id(char), id(int), expires_at(ts), refresh_token(char), client(char), refresh_error(text), grant_type(char), cc_client_id(char), cc_client_secret(char), cc_token_url(char), mcp_server_url(text), scopes(text[]) FK: (workspace_id) -> workspace(id) agent_token_blacklist: token(char), expires_at(ts), blacklisted_at(ts), blacklisted_by(char) -ai_agent_checkpoint: job_id(uuid), workspace_id(char), checkpoint(jsonb), created_at(ts) +ai_agent_checkpoint: job_id(uuid), workspace_id(char), checkpoint(jsonb), created_at(ts), waiting_on(uuid[]) ai_agent_memory: workspace_id(char), conversation_id(uuid), step_id(char), messages(jsonb), created_at(ts), updated_at(ts) 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_memory_turn: workspace_id(char), memory_id(uuid), job_id(uuid) 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) @@ -59,7 +60,9 @@ app_version_lite: id(bigint), value(jsonb) asset: workspace_id(char), path(char), kind(asset_kind), usage_access_type(asset_access_type), usage_path(char), usage_kind(asset_usage_kind), created_at(ts), id(bigint), columns(jsonb) FK: (workspace_id) -> workspace(id) audit_partitioned: workspace_id(char), id(bigint), timestamp(ts), username(char), operation(char), action_kind(action_kind), resource(char), parameters(jsonb), email(char), span(char) +autoscaling_decision: id(bigint), worker_group(text), recorded_at(ts), worker_count(int), occupancy_rate_15s(real), occupancy_rate_5m(real), occupancy_rate_30m(real), jobs_waiting(jsonb), decision(text) autoscaling_event: id(int), worker_group(text), event_type(autoscaling_event_type), desired_workers(int), applied_at(ts), reason(text) +autoscaling_recording: worker_group(text), until(ts), started_by(text) capture: workspace_id(char), path(char), created_at(ts), created_by(char), main_args(jsonb), is_flow(bool), trigger_kind(trigger_kind), preprocessor_args(jsonb), id(bigint) FK: (workspace_id) -> workspace(id) capture_config: workspace_id(char), path(char), is_flow(bool), trigger_kind(trigger_kind), trigger_config(jsonb), owner(char), email(char), server_id(char), last_client_ping(ts), last_server_ping(ts), error(text) diff --git a/backend/tests/access_view.rs b/backend/tests/access_view.rs index 106ea86240..2c613eefd7 100644 --- a/backend/tests/access_view.rs +++ b/backend/tests/access_view.rs @@ -122,6 +122,15 @@ async fn test_browse_items_kind_and_blocked(db: Pool) -> anyhow::Resul .await?; assert_eq!(admin["items"][0]["blocked"], serde_json::Value::Null); + // A mistyped principal is refused rather than listed as holding nothing. + let resp = reqwest::Client::new() + .get(&url) + .query(&[("principal", "g/does_not_exist")]) + .header("Authorization", "Bearer SECRET_TOKEN") + .send() + .await?; + assert_eq!(resp.status(), 404, "{}", resp.text().await?); + Ok(()) } diff --git a/backend/tests/agent_workers.rs b/backend/tests/agent_workers.rs index 4d6fffa346..81df086fa1 100644 --- a/backend/tests/agent_workers.rs +++ b/backend/tests/agent_workers.rs @@ -528,6 +528,146 @@ export function main() { Ok(()) } +/// Every test that sets the fleet's minimum version holds this: tests share the process. +#[cfg(all(feature = "parquet", feature = "enterprise"))] +static FLEET_VERSION: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +#[cfg(all(feature = "parquet", feature = "enterprise"))] +struct OnDrop(F); + +#[cfg(all(feature = "parquet", feature = "enterprise"))] +impl Drop for OnDrop { + fn drop(&mut self) { + (self.0)() + } +} + +/// An agent worker's `volume:ro` pull takes no lease, waits for a write in progress to close, +/// and writes nothing back. +#[cfg(all(feature = "parquet", feature = "enterprise"))] +#[sqlx::test(fixtures("base"))] +async fn test_agent_worker_read_only_volume(db: Pool) -> anyhow::Result<()> { + let leased_by = run_agent_read_only_volume(db, true).await?; + assert_eq!(leased_by.as_deref(), Some("other-worker")); + Ok(()) +} + +/// Until every worker marks its writes, a `volume:ro` mount pulls under the lease, and holding +/// it must not make the mount writable. +#[cfg(all(feature = "parquet", feature = "enterprise"))] +#[sqlx::test(fixtures("base"))] +async fn test_agent_worker_read_only_volume_leased(db: Pool) -> anyhow::Result<()> { + let leased_by = run_agent_read_only_volume(db, false).await?; + assert_eq!(leased_by, None, "the lease should be released"); + Ok(()) +} + +/// Another worker holds the volume and rewrites `hello.txt` after 3s: under a write window +/// (odd generation, lease held for an hour) when the fleet supports lease-free pulls, or as an +/// older worker would, with no window and a lease that lapses after 4s. Either way the +/// `volume:ro` job must read the rewritten file and leave nothing behind. Returns `leased_by`. +#[cfg(all(feature = "parquet", feature = "enterprise"))] +async fn run_agent_read_only_volume( + db: Pool, + fleet_supports_lease_free: bool, +) -> anyhow::Result> { + use windmill_common::min_version::{MIN_VERSION, MIN_VERSION_SUPPORTS_LEASE_FREE_VOLUMES}; + let _fleet = FLEET_VERSION.lock().await; + // Put back for the rest of the binary, panics included + let before = MIN_VERSION.load_full(); + let _restore = OnDrop(move || MIN_VERSION.store(before.clone())); + let mut fleet = MIN_VERSION_SUPPORTS_LEASE_FREE_VOLUMES.version().clone(); + if !fleet_supports_lease_free { + fleet.minor -= 1; + } + MIN_VERSION.store(std::sync::Arc::new(fleet)); + + let (_client, port, _server) = init_client_agent_mode(db.clone()).await; + + let storage_dir = tempfile::tempdir()?; + let lfs_config = json!({ + "type": "FilesystemStorage", + "root_path": storage_dir.path().to_string_lossy(), + "public_resource": null, + "advanced_permissions": null, + "volume_storage": "primary" + }); + sqlx::query!( + "UPDATE workspace_settings SET large_file_storage = $1 WHERE workspace_id = 'test-workspace'", + lfs_config, + ) + .execute(&db) + .await?; + let vol_dir = storage_dir.path().join("volumes/test-workspace/test-vol"); + std::fs::create_dir_all(&vol_dir)?; + std::fs::write(vol_dir.join("hello.txt"), b"hello from volume")?; + + let (lease_secs, generation) = if fleet_supports_lease_free { + (3600, 1) + } else { + (4, 0) + }; + sqlx::query!( + "INSERT INTO volume (workspace_id, name, size_bytes, created_by, lease_until, leased_by, generation) + VALUES ('test-workspace', 'test-vol', 0, 'test-user', now() + make_interval(secs => $1), 'other-worker', $2)", + lease_secs as f64, + generation + ) + .execute(&db) + .await?; + let db_c = db.clone(); + let hello = vol_dir.join("hello.txt"); + let writer = tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_secs(3)).await; + std::fs::write(&hello, b"hello after the write").unwrap(); + if fleet_supports_lease_free { + sqlx::query!( + "UPDATE volume SET generation = 2 WHERE workspace_id = 'test-workspace' AND name = 'test-vol'" + ) + .execute(&db_c) + .await?; + } + Ok::<_, sqlx::Error>(()) + }); + + let code = r#"// volume:ro test-vol data +import { readFileSync, writeFileSync } from "fs"; + +export function main() { + const content = readFileSync("data/hello.txt", "utf-8"); + writeFileSync("data/output.txt", "discarded"); + return { read_content: content }; +}"#; + let uuid = RunJob::from(JobPayload::Code(bun_code(code))) + .push(&db) + .await; + let listener = listen_for_completed_jobs(&db).await; + let conn = testing_http_connection_with_tags( + port, + vec!["bun".into(), "flow".into(), "dependency".into()], + ) + .await; + in_test_worker(conn, listener.find(&uuid), port).await; + writer.await??; + + let result = completed_job(uuid, &db).await; + assert!(result.success, "job should succeed: {:?}", result.result); + assert_eq!( + result.json_result().unwrap()["read_content"], + json!("hello after the write"), + "the pull must wait for the other worker's write" + ); + assert!( + !vol_dir.join("output.txt").exists(), + "a read-only mount must not write back" + ); + Ok(sqlx::query_scalar!( + "SELECT leased_by FROM volume WHERE workspace_id = 'test-workspace' AND name = 'test-vol'" + ) + .fetch_one(&db) + .await?) +} + /// Test the volume release endpoint (error/cancel path). #[cfg(feature = "parquet")] #[sqlx::test(fixtures("base"))] diff --git a/backend/tests/ai_agent_tool_scope.rs b/backend/tests/ai_agent_tool_scope.rs new file mode 100644 index 0000000000..7037a297fc --- /dev/null +++ b/backend/tests/ai_agent_tool_scope.rs @@ -0,0 +1,181 @@ +use axum::{routing::post, Json, Router}; +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use std::time::Duration; +use uuid::Uuid; +use windmill_common::{flows::FlowValue, jobs::JobPayload}; +use windmill_test_utils::{ + completed_job, in_test_worker, listen_for_completed_jobs, ApiServer, RunJob, StreamFind, +}; + +const CONVERSATION: Uuid = Uuid::from_u128(0xc0de); + +/// A model that calls every tool it is offered once, then answers. +async fn model(Json(body): Json) -> ([(&'static str, &'static str); 1], String) { + let finished = body["messages"] + .as_array() + .unwrap() + .iter() + .any(|m| m["role"] == "tool"); + let delta = if finished { + json!({"role":"assistant", "content":"done"}) + } else { + let calls: Vec = body["tools"] + .as_array() + .unwrap() + .iter() + .enumerate() + .map(|(i, tool)| { + json!({ + "index":i, "id":format!("call_{i}"), "type":"function", + "function":{"name":tool["function"]["name"], "arguments":"{}"} + }) + }) + .collect(); + json!({"role":"assistant", "tool_calls":calls}) + }; + let event = json!({"choices":[{"index":0, "delta":delta, "finish_reason":null}]}); + let end = json!({"choices":[{"index":0, "delta":{}, "finish_reason":if finished {"stop"} else {"tool_calls"}}]}); + ( + [("content-type", "text/event-stream")], + format!("data: {event}\n\ndata: {end}\n\ndata: [DONE]\n\n"), + ) +} + +fn record_tool(id: &str) -> Value { + json!({"id":id,"summary":"record","value":{ + "type":"rawscript", "language":"bun", + "input_transforms":{ + "topic":{"type":"javascript","expr":"flow_input.iter.value"}, + "prev":{"type":"javascript","expr":"results.a"}, + "pr":{"type":"javascript","expr":"previous_result"}, + "state":{"type":"javascript","expr":"flow_user_state('k')"} + }, + "content":"export async function main(topic: string, prev: string, pr: string, state: string) { return `${topic}|${prev}|${pr}|${state}` }" + }}) +} + +/// A loop body runs as its own flow job, as a subflow does: a tool's `flow_input` and `results` +/// must be that flow's, as a regular step's are, not the root run's. A nested agent's tools read +/// the same flow, past the agent calling it, and the run's user state. An agent first in its flow +/// gets that flow's args as `previous_result`, as a regular first step does. In a chat run, only the calling agent writes to the +/// conversation, and every row it writes belongs to the run. +#[sqlx::test(fixtures("base"))] +#[serial_test::serial] +async fn agent_tool_reads_inputs_of_the_flow_running_the_step( + db: Pool, +) -> anyhow::Result<()> { + std::env::set_var("ALLOW_PRIVATE_AI_BASE_URLS", "true"); + let server = ApiServer::start(db.clone()).await?; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let base = format!("http://{}", listener.local_addr()?); + let stub = tokio::spawn(async move { + let router = Router::new().route("/v1/chat/completions", post(model)); + axum::serve(listener, router).await.unwrap(); + }); + let agent_inputs = json!({ + "provider":{"type":"static","value":{"kind":"customai","model":"scope-test","resource":{"base_url":format!("{base}/v1")}}}, + "user_message":{"type":"static","value":"record"} + }); + let flow: FlowValue = serde_json::from_value( + json!({"chat_input_enabled":true,"modules":[{"id":"loop","value":{ + "type":"forloopflow", + "iterator":{"type":"javascript","expr":"['t1', 't2']"}, + "skip_failures":false, + "modules":[ + {"id":"first","value":{ + "type":"aiagent", + "tools":[{"id":"first_record","summary":"record","value":{ + "type":"rawscript", "language":"bun", + "input_transforms":{"pr":{"type":"javascript","expr":"previous_result"}}, + "content":"export async function main(pr: any) { return `first|${pr.iter.value}` }" + }}], + "input_transforms":agent_inputs.clone() + }}, + {"id":"a","value":{ + "type":"rawscript", "language":"bun", + "input_transforms":{"topic":{"type":"javascript","expr":"flow_input.iter.value"}}, + "content":"export async function main(topic: string) { return 'seed-' + topic }" + }}, + {"id":"agent","value":{ + "type":"aiagent", + "tools":[ + record_tool("record"), + {"id":"inner","summary":"inner","value":{ + "type":"aiagent", + "tools":[record_tool("inner_record")], + "input_transforms":agent_inputs.clone() + }} + ], + "input_transforms":agent_inputs + }} + ] + }}]}), + )?; + let id = RunJob::from(JobPayload::RawFlow { + value: flow, + path: Some("u/test/agent_tool_scope".into()), + restarted_from: None, + }) + .push(&db) + .await; + // What the API does for a chat turn: open the conversation and give the run its id. + sqlx::query( + "INSERT INTO flow_conversation (id, workspace_id, flow_path, created_by) + VALUES ($1, 'test-workspace', 'u/test/agent_tool_scope', 'test-user')", + ) + .bind(CONVERSATION) + .execute(&db) + .await?; + sqlx::query( + "UPDATE v2_job_status SET flow_status = jsonb_set(flow_status, '{memory_id}', to_jsonb($2::uuid)) + || jsonb_build_object('user_states', jsonb_build_object('k', 'v')) + WHERE id = $1", + ) + .bind(id) + .bind(CONVERSATION) + .execute(&db) + .await?; + let notifications = listen_for_completed_jobs(&db).await; + tokio::time::timeout( + Duration::from_secs(60), + in_test_worker(&db, notifications.find(&id), server.addr.port()), + ) + .await?; + let job = completed_job(id, &db).await; + stub.abort(); + server.close().await?; + assert!(job.success, "{:?}", job.result); + let recorded: Vec<(String, Value)> = sqlx::query_as( + "SELECT j.runnable_path, c.result FROM v2_job j JOIN v2_job_completed c USING(id) + WHERE j.runnable_path LIKE '%/tools/%record' ORDER BY c.result::text, j.runnable_path", + ) + .fetch_all(&db) + .await? + .into_iter() + .map(|(path, result): (String, sqlx::types::Json)| (path, result.0)) + .collect(); + let results: Vec<&Value> = recorded.iter().map(|(_, r)| r).collect(); + assert_eq!( + results, + vec![ + &json!("first|t1"), + &json!("first|t2"), + &json!("t1|seed-t1|seed-t1|v"), + &json!("t1|seed-t1|seed-t1|v"), + &json!("t2|seed-t2|seed-t2|v"), + &json!("t2|seed-t2|seed-t2|v") + ], + "{recorded:?}" + ); + // A row the nested agent wrote would carry the calling agent's job as its turn. + let turns: Vec = sqlx::query_scalar( + "SELECT turn_job_id FROM flow_conversation_message WHERE conversation_id = $1", + ) + .bind(CONVERSATION) + .fetch_all(&db) + .await?; + assert!(!turns.is_empty()); + assert!(turns.iter().all(|turn| *turn == id), "{turns:?}"); + Ok(()) +} diff --git a/backend/tests/ai_decision.rs b/backend/tests/ai_decision.rs index d6359c1cea..c64eae3100 100644 --- a/backend/tests/ai_decision.rs +++ b/backend/tests/ai_decision.rs @@ -1,6 +1,6 @@ //! AI decision steps run end to end against a stand-in for the decision endpoints: TypeSafe's //! System One, Cloudflare Workers AI's, which serves each model at its own URL inside an API -//! envelope, and OpenAI's Decisions API. +//! envelope, and OpenAI's and Gemini's Decisions APIs. use axum::{routing::post, Json, Router}; use serde_json::{json, Value}; @@ -51,6 +51,22 @@ async fn start_decision_stub() -> anyhow::Result { .collect::>(); Json(json!({"answers": answers})) }), + ) + // Gemini's keys the questions as System One does, and authenticates with its own header. + .route( + "/gemini/v1beta/decisions", + post( + |headers: axum::http::HeaderMap, Json(body): Json| async move { + if headers.get("x-goog-api-key").and_then(|v| v.to_str().ok()) != Some("key") + || body["input"] != "I was charged twice" + { + return Err(axum::http::StatusCode::UNAUTHORIZED); + } + let mut answers = refund_answers(&body); + answers["usage"] = json!({"total_input_tokens": 10, "total_output_tokens": 0}); + Ok(Json(answers)) + }, + ), ); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; let port = listener.local_addr()?.port(); @@ -91,6 +107,11 @@ async fn test_ai_decision_answers_route_a_following_branch( "resource": {"api_key": "key", "base_url": format!("http://127.0.0.1:{stub_port}/openai/v1")}, "model": "gpt-6-luna" }), + json!({ + "kind": "googleai", + "resource": {"api_key": "key", "base_url": format!("http://127.0.0.1:{stub_port}/gemini/v1beta")}, + "model": "gemini-decision-1" + }), ] { let flow: FlowValue = serde_json::from_value(json!({ "modules": [ diff --git a/backend/tests/ai_memory_turn.rs b/backend/tests/ai_memory_turn.rs new file mode 100644 index 0000000000..1564c83a59 --- /dev/null +++ b/backend/tests/ai_memory_turn.rs @@ -0,0 +1,244 @@ +//! A memory id is held by one queued run at a time: a second run that claims it is refused, even +//! when both claim at once, and the id is free again once its run leaves the queue. A run whose +//! AI agent is parked at its last step hands the id over instead. + +use sqlx::{Pool, Postgres, Transaction}; +use uuid::Uuid; +use windmill_api::jobs::set_flow_memory_id; +use windmill_common::error::Error; +use windmill_test_utils::*; + +const WS: &str = "test-workspace"; +const MEMORY: Uuid = Uuid::from_u128(0x3e3); + +/// Queue a run in `tx` and claim the memory id for it, as a push does. +async fn push_with_memory(tx: &mut Transaction<'_, Postgres>) -> anyhow::Result<(Uuid, bool)> { + let job_id = Uuid::new_v4(); + sqlx::query!( + "INSERT INTO v2_job (id, workspace_id, kind) VALUES ($1, $2, 'flow')", + job_id, + WS + ) + .execute(&mut **tx) + .await?; + sqlx::query!( + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for) VALUES ($1, $2, now())", + job_id, + WS + ) + .execute(&mut **tx) + .await?; + match set_flow_memory_id(tx, WS, job_id, MEMORY).await { + Ok(()) => Ok((job_id, true)), + Err(Error::Generic(status, _)) if status.as_u16() == 409 => Ok((job_id, false)), + Err(e) => Err(e.into()), + } +} + +#[sqlx::test(fixtures("base"))] +async fn test_one_queued_run_holds_a_memory_id(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + // Two claims at once: the second waits on the first's row, then must see its run queued. + let mut first = db.begin().await?; + let (first_job, claimed) = push_with_memory(&mut first).await?; + assert!(claimed); + let second = tokio::spawn({ + let db = db.clone(); + async move { + let mut tx = db.begin().await?; + let outcome = push_with_memory(&mut tx).await?; + tx.commit().await?; + anyhow::Ok(outcome) + } + }); + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + first.commit().await?; + let (_, claimed) = second.await??; + assert!( + !claimed, + "a run claimed the memory id another queued run holds" + ); + + // Once the holder leaves the queue, the next run takes the id over. + sqlx::query!("DELETE FROM v2_job_queue WHERE id = $1", first_job) + .execute(&db) + .await?; + let mut tx = db.begin().await?; + let (third_job, claimed) = push_with_memory(&mut tx).await?; + tx.commit().await?; + assert!(claimed); + let holder = sqlx::query_scalar!( + "SELECT job_id FROM ai_memory_turn WHERE workspace_id = $1 AND memory_id = $2", + WS, + MEMORY + ) + .fetch_one(&db) + .await?; + assert_eq!(holder, third_job); + Ok(()) +} + +/// A queued run holding the memory id, at step `at` of `steps` top-level steps, where an AI agent +/// step is parked on one background job. Returns the agent's job. +async fn hold_with_parked_agent( + db: &Pool, + steps: usize, + at: usize, +) -> anyhow::Result { + let mut tx = db.begin().await?; + let (holder, claimed) = push_with_memory(&mut tx).await?; + assert!(claimed); + let agent = Uuid::new_v4(); + let modules: Vec = (0..steps) + .map(|i| match i == at { + true => serde_json::json!({ "type": "InProgress", "id": "a", "job": agent }), + false => serde_json::json!({ "type": "WaitingForPriorSteps", "id": format!("s{i}") }), + }) + .collect(); + let flow_status = serde_json::json!({ "step": at, "modules": modules }); + sqlx::query!( + "INSERT INTO v2_job_status (id, flow_status) VALUES ($1, $2)", + holder, + flow_status + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "INSERT INTO v2_job (id, workspace_id, kind, parent_job, flow_step_id) + VALUES ($1, $2, 'aiagent', $3, 'a')", + agent, + WS, + holder + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, suspend, suspend_until) + VALUES ($1, $2, now(), 1, now() + interval '1 hour')", + agent, + WS + ) + .execute(&mut *tx) + .await?; + let checkpoint = serde_json::json!({ "background": [{ "job_id": BACKGROUND_JOB }] }); + sqlx::query!( + "INSERT INTO ai_agent_checkpoint (job_id, workspace_id, checkpoint, waiting_on) + VALUES ($1, $2, $3, $4)", + agent, + WS, + checkpoint, + &[BACKGROUND_JOB] + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "INSERT INTO v2_job (id, workspace_id, kind, parent_job, root_job) + VALUES ($1, $2, 'script', $3, $4)", + BACKGROUND_JOB, + WS, + agent, + holder + ) + .execute(&mut *tx) + .await?; + // A nested agent's own background job, under the handed one. + sqlx::query!( + "INSERT INTO v2_job (id, workspace_id, kind, parent_job, root_job) + VALUES ($1, $2, 'script', $3, $4)", + NESTED_JOB, + WS, + BACKGROUND_JOB, + holder + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for) + VALUES ($1, $2, now()), ($3, $2, now())", + BACKGROUND_JOB, + WS, + NESTED_JOB + ) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(agent) +} + +const BACKGROUND_JOB: Uuid = Uuid::from_u128(0xb6); +const NESTED_JOB: Uuid = Uuid::from_u128(0xb7); + +#[sqlx::test(fixtures("base"))] +async fn test_a_parked_last_step_hands_its_memory_id_over( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let agent = hold_with_parked_agent(&db, 2, 1).await?; + + let mut tx = db.begin().await?; + let (new_run, claimed) = push_with_memory(&mut tx).await?; + tx.commit().await?; + assert!(claimed, "a run parked at its last step refused a new one"); + + let turn = sqlx::query!( + "SELECT job_id, handed_jobs FROM ai_memory_turn WHERE workspace_id = $1 AND memory_id = $2", + WS, + MEMORY + ) + .fetch_one(&db) + .await?; + assert_eq!(turn.job_id, new_run); + assert_eq!( + turn.handed_jobs, + Some(serde_json::json!({ "a": [{ "job_id": BACKGROUND_JOB }] })) + ); + let woken = sqlx::query!( + r#"SELECT q.suspend, c.checkpoint->'handed_over' AS "handed_over", c.waiting_on + FROM v2_job_queue q JOIN ai_agent_checkpoint c ON c.job_id = q.id WHERE q.id = $1"#, + agent + ) + .fetch_one(&db) + .await?; + assert_eq!(woken.suspend, 0); + assert_eq!(woken.handed_over, Some(serde_json::json!(true))); + assert!(woken.waiting_on.is_empty()); + // The new run ends before its agent adopts the job: the next claim cancels it. + sqlx::query!("DELETE FROM v2_job_queue WHERE id = $1", new_run) + .execute(&db) + .await?; + let mut tx = db.begin().await?; + let (_, claimed) = push_with_memory(&mut tx).await?; + tx.commit().await?; + assert!(claimed); + let cancelled = sqlx::query_scalar!( + "SELECT canceled_by FROM v2_job_queue WHERE id = ANY($1)", + &[BACKGROUND_JOB, NESTED_JOB] + ) + .fetch_all(&db) + .await?; + assert_eq!(cancelled, vec![Some("monitor".to_string()); 2]); + Ok(()) +} + +#[sqlx::test(fixtures("base"))] +async fn test_a_parked_step_with_steps_after_it_keeps_its_memory_id( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let agent = hold_with_parked_agent(&db, 2, 0).await?; + + let mut tx = db.begin().await?; + let (_, claimed) = push_with_memory(&mut tx).await?; + tx.rollback().await?; + assert!( + !claimed, + "a run with a step after its parked agent handed its memory id over" + ); + + let suspend = sqlx::query_scalar!("SELECT suspend FROM v2_job_queue WHERE id = $1", agent) + .fetch_one(&db) + .await?; + assert_eq!(suspend, 1, "the refused hand-over woke the parked agent"); + Ok(()) +} diff --git a/backend/tests/ai_shared_sessions.rs b/backend/tests/ai_shared_sessions.rs index 75334a5440..424465fd20 100644 --- a/backend/tests/ai_shared_sessions.rs +++ b/backend/tests/ai_shared_sessions.rs @@ -118,3 +118,70 @@ async fn private_share_is_for_members_and_public_share_for_anyone( Ok(()) } + +#[sqlx::test(fixtures("base"))] +async fn a_share_is_listed_for_a_member_only_once_they_open_it( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().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 client = reqwest::Client::new(); + + let share: Value = client + .post(format!("{authed}/share")) + .header("Authorization", MEMBER) + .json(&json!({ + "session_id": "session-1", + "name": "Debugging", + "message_count": 1, + "snapshot": { "messages": [], "artifacts": [] }, + })) + .send() + .await? + .json() + .await?; + let id = share["id"].as_str().unwrap().to_string(); + + let listed = |token: &'static str| { + let req = client + .get(format!("{authed}/list")) + .header("Authorization", token); + async move { anyhow::Ok(req.send().await?.json::>().await?) } + }; + + let mine = listed(MEMBER).await?; + assert_eq!(mine.len(), 1, "the author does not see their own share"); + assert_eq!(mine[0]["session_id"], "session-1"); + assert!( + listed(OTHER_MEMBER).await?.is_empty(), + "a share was listed for a member who never opened its link" + ); + + let resp = client + .get(format!( + "http://localhost:{port}/api/w/test-workspace/ai_u/shared_sessions/get/{id}" + )) + .header("Authorization", OTHER_MEMBER) + .send() + .await?; + assert_eq!(resp.status(), 200); + let opened = listed(OTHER_MEMBER).await?; + assert_eq!(opened.len(), 1, "opening the link did not list the share"); + assert!( + opened[0].get("session_id").is_none(), + "the author's session id was sent to a reader" + ); + assert!(opened[0]["opened_at"].is_string()); + + let resp = client + .delete(format!("{authed}/opened/{id}")) + .header("Authorization", OTHER_MEMBER) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + assert!(listed(OTHER_MEMBER).await?.is_empty()); + + Ok(()) +} diff --git a/backend/tests/app_public_cloud_plan.rs b/backend/tests/app_public_cloud_plan.rs new file mode 100644 index 0000000000..d2101fb7a3 --- /dev/null +++ b/backend/tests/app_public_cloud_plan.rs @@ -0,0 +1,104 @@ +//! On the shared cloud (`CLOUD_HOSTED`), public (`anonymous`) apps take a paid plan. +//! +//! One test in its own binary on purpose: `CLOUD_HOSTED` is read once into a +//! `lazy_static`, so it must be set before anything reads it. +#![cfg(feature = "cloud")] + +use serde_json::json; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +const ADMIN_TOKEN: &str = "SECRET_TOKEN"; +const APP_PATH: &str = "u/test-user/public_app"; + +fn post(url: String) -> reqwest::RequestBuilder { + reqwest::Client::new() + .post(url) + .header("Authorization", format!("Bearer {ADMIN_TOKEN}")) +} + +fn public_app() -> serde_json::Value { + json!({ + "path": APP_PATH, + "summary": "Public app", + "value": {}, + "policy": { "execution_mode": "anonymous", "triggerables": {} } + }) +} + +#[sqlx::test(fixtures("base"))] +async fn public_apps_take_a_paid_plan(db: Pool) -> anyhow::Result<()> { + unsafe { std::env::set_var("CLOUD_HOSTED", "true") }; + initialize_tracing().await; + // A fork of a paid root draws the root's plan, though it is not premium itself. + sqlx::raw_sql( + "INSERT INTO workspace (id, name, owner, premium) VALUES ('paid-root', 'paid-root', 'test-user', true); + INSERT INTO workspace (id, name, owner, parent_workspace_id) + VALUES ('paid-fork', 'paid-fork', 'test-user', 'paid-root'); + INSERT INTO workspace_settings (workspace_id) VALUES ('paid-root'), ('paid-fork'); + INSERT INTO usr (workspace_id, email, username, is_admin, role) + VALUES ('paid-fork', 'test@windmill.dev', 'test-user', true, 'Admin');", + ) + .execute(&db) + .await?; + let server = ApiServer::start(db.clone()).await?; + let api = format!("http://localhost:{}/api/w", server.addr.port()); + let ws = format!("{api}/test-workspace"); + + let resp = post(format!("{ws}/apps/create")) + .json(&public_app()) + .send() + .await?; + assert_eq!( + resp.status(), + 400, + "a free workspace cannot create a public app" + ); + assert!(resp.text().await?.contains("paid plan")); + + // An app made public before the rule: its next version is refused too. + let mut app = public_app(); + app["policy"]["execution_mode"] = json!("publisher"); + let resp = post(format!("{ws}/apps/create")).json(&app).send().await?; + assert_eq!(resp.status(), 201, "{}", resp.text().await?); + let resp = post(format!("{ws}/apps/update/{APP_PATH}")) + .json(&json!({ "execution_mode": "anonymous" })) + .send() + .await?; + assert_eq!(resp.status(), 400, "an app cannot be switched to public"); + sqlx::query( + "UPDATE app SET policy = jsonb_set(policy, '{execution_mode}', '\"anonymous\"') + WHERE path = $1 AND workspace_id = 'test-workspace'", + ) + .bind(APP_PATH) + .execute(&db) + .await?; + let resp = post(format!("{ws}/apps/update/{APP_PATH}")) + .json(&json!({ "value": { "grid": [] } })) + .send() + .await?; + assert_eq!( + resp.status(), + 400, + "an already-public app cannot be redeployed" + ); + + // Taking it out of public stays allowed. + let resp = post(format!("{ws}/apps/update/{APP_PATH}")) + .json(&json!({ "execution_mode": "publisher" })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let resp = post(format!("{api}/paid-fork/apps/create")) + .json(&public_app()) + .send() + .await?; + assert_eq!( + resp.status(), + 201, + "a fork of a paid root may publish: {}", + resp.text().await? + ); + Ok(()) +} diff --git a/backend/tests/bun_jobs.rs b/backend/tests/bun_jobs.rs index 071842ae16..1a273f68c5 100644 --- a/backend/tests/bun_jobs.rs +++ b/backend/tests/bun_jobs.rs @@ -1710,7 +1710,7 @@ mod dedicated_worker_protocol { runtime: &str, script: &str, jobs: Vec, - ) -> Vec> { + ) -> Vec> { let temp_dir = tempfile::tempdir().unwrap(); // Create files and get the wrapper path (bundled for node, raw for bun) @@ -1767,13 +1767,7 @@ mod dedicated_worker_protocol { match parse_dedicated_worker_line(response.trim()) { DedicatedWorkerResult::Success(value) => results.push(Ok(value)), - DedicatedWorkerResult::Error(err) => { - let msg = err["message"] - .as_str() - .unwrap_or("Unknown error") - .to_string(); - results.push(Err(msg)); - } + DedicatedWorkerResult::Error(err) => results.push(Err(err)), other => panic!("Unexpected response: {:?}", other), } } @@ -1831,8 +1825,7 @@ export function main(msg: string): never { ); assert_eq!(results.len(), 1); - assert!(results[0].is_err()); - assert_eq!(results[0], Err("test error".to_string())); + assert_eq!(results[0].as_ref().unwrap_err()["message"], "test error"); } // ==================== Bun Runtime Tests ==================== @@ -1871,7 +1864,7 @@ export function main(n: number): number { fn test_dedicated_worker_bun_error() { let script = r#" export function main(msg: string): never { - throw new Error(msg); + throw Object.assign(new Error(msg), { code: 42 }); } "#; let results = run_worker_test( @@ -1881,8 +1874,13 @@ export function main(msg: string): never { ); assert_eq!(results.len(), 1); - assert!(results[0].is_err()); - assert_eq!(results[0], Err("test error".to_string())); + let err = results[0].as_ref().unwrap_err(); + assert_eq!(err["message"], "test error"); + assert_eq!(err["extra"], serde_json::json!({ "code": 42 })); + assert!( + err.get("line").is_none(), + "job args leaked into the error: {err}" + ); } // ==================== Multi-Script (Runner Group) Tests ==================== diff --git a/backend/tests/ci_tests.rs b/backend/tests/ci_tests.rs index 46bed97094..4f4abc2f49 100644 --- a/backend/tests/ci_tests.rs +++ b/backend/tests/ci_tests.rs @@ -113,4 +113,82 @@ mod ci_tests { Ok(()) } + + /// A deploy made with `skip_ci_tests` queues no test, even from its dependency job, and + /// the batch trigger holds the tests back until that lock has landed. + #[sqlx::test(fixtures("base"))] + async fn test_ci_tests_deferred_to_batch(db: Pool) -> anyhow::Result<()> { + let (client, port, _s) = init_client(db.clone()).await; + let bun_ns = |content: &str, path: &str| NewScript { + language: ScriptLang::Bun, + ..quick_ns(content, path, None) + }; + client + .create_script( + "test-workspace", + &bun_ns( + "// test: script/u/test-user/batch_target\nexport function main() { return true }", + "u/test-user/ci_test_for_batch", + ), + ) + .await + .unwrap(); + let mut completed = listen_for_completed_jobs(&db).await; + in_test_worker(&db, completed.next(), port).await; + + let http = reqwest::Client::new(); + let api = format!("http://localhost:{port}/api/w/test-workspace/scripts"); + http.post(format!("{api}/create?skip_ci_tests=true")) + .bearer_auth("SECRET_TOKEN") + .json(&bun_ns( + "export function main() { return 42 }", + "u/test-user/batch_target", + )) + .send() + .await? + .error_for_status()?; + + let trigger_batch = || async { + http.post(format!("{api}/trigger_ci_tests_batch")) + .bearer_auth("SECRET_TOKEN") + .json(&serde_json::json!({ + "items": [{ "kind": "script", "path": "u/test-user/batch_target" }] + })) + .send() + .await? + .error_for_status()? + .json::() + .await + }; + let ci_jobs = || { + sqlx::query_scalar!( + "SELECT count(*) FROM v2_job WHERE workspace_id = 'test-workspace' \ + AND trigger_kind = 'ci_test'" + ) + .fetch_one(&db) + }; + + let pending = trigger_batch().await?; + assert_eq!( + pending["pending"], + serde_json::json!(["u/test-user/batch_target"]) + ); + assert_eq!(pending["job_ids"], serde_json::json!([])); + + let mut completed = listen_for_completed_jobs(&db).await; + in_test_worker(&db, completed.next(), port).await; + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + assert_eq!( + ci_jobs().await?, + Some(0), + "the lock generation queued a CI test" + ); + + let triggered = trigger_batch().await?; + assert_eq!(triggered["pending"], serde_json::json!([])); + assert_eq!(triggered["job_ids"].as_array().map(|a| a.len()), Some(1)); + assert_eq!(ci_jobs().await?, Some(1)); + + Ok(()) + } } diff --git a/backend/tests/dependency_job_tag.rs b/backend/tests/dependency_job_tag.rs index 58b320d2c1..af39ebb061 100644 --- a/backend/tests/dependency_job_tag.rs +++ b/backend/tests/dependency_job_tag.rs @@ -40,6 +40,7 @@ async fn relocks_go_to_the_configured_dependency_job_tag(db: Pool) -> "u/test-user", &db, vec![], + false, ) .await?; diff --git a/backend/tests/dependency_map.rs b/backend/tests/dependency_map.rs index 874e83f1be..6dbc029276 100644 --- a/backend/tests/dependency_map.rs +++ b/backend/tests/dependency_map.rs @@ -577,6 +577,7 @@ def main(): "u/test-user", &db, vec![], + false, ) .await?; @@ -631,6 +632,7 @@ def main(): "u/test-user", &db, vec![], + false, ) .await?; diff --git a/backend/tests/end_user_email.rs b/backend/tests/end_user_email.rs index bde142ef69..8d6c0d167c 100644 --- a/backend/tests/end_user_email.rs +++ b/backend/tests/end_user_email.rs @@ -360,6 +360,7 @@ async fn test_job_token_run_keeps_end_user_email(db: Pool) -> anyhow:: scopes: None, token_prefix: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), }, "test-workspace", 3600, diff --git a/backend/tests/fixtures/relative_python.sql b/backend/tests/fixtures/relative_python.sql index 7a70e06d20..40fbedfc34 100644 --- a/backend/tests/fixtures/relative_python.sql +++ b/backend/tests/fixtures/relative_python.sql @@ -38,3 +38,24 @@ def main(): '', '', 'f/system_relative/nested_script', 12348, 'python3', ''); + +-- Named after files in the job dir (loader.py) and after the running script's folder (f/system/). +INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( +'test-workspace', +'test-user', +'from .different_folder_script import main +', +'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', +'', +'', +'f/system_relative/loader', 12349, 'python3', ''); + +INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( +'test-workspace', +'test-user', +'from .different_folder_script import main +', +'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', +'', +'', +'f/system_relative/system', 12350, 'python3', ''); diff --git a/backend/tests/flow_engine_parity.rs b/backend/tests/flow_engine_parity.rs index 2d4f72f336..98f7bc0f95 100644 --- a/backend/tests/flow_engine_parity.rs +++ b/backend/tests/flow_engine_parity.rs @@ -188,6 +188,7 @@ export function main() { skip_failures: false, parallel: false, squash: None, + iteration_label: None, parallelism: None, modules: vec![flow_module( "c", @@ -531,6 +532,7 @@ export function main() { skip_failures: false, parallel: false, squash: None, + iteration_label: None, parallelism: None, modules: vec![ // For each category, compute results using base_values @@ -980,6 +982,7 @@ export function main() { skip_failures: false, parallel: true, squash: None, + iteration_label: None, parallelism: None, modules: vec![flow_module( "process", @@ -1897,6 +1900,7 @@ export function main() { skip_failures: false, parallel: false, squash: None, + iteration_label: None, parallelism: None, modules: vec![ // Step b: generate inner items based on category @@ -2539,6 +2543,7 @@ export function main() { parallel: true, parallelism: None, squash: None, + iteration_label: None, }, )], flow_env: Some(flow_env), @@ -3301,6 +3306,7 @@ export function main(i: number) { parallel: false, parallelism: None, squash: None, + iteration_label: None, }, ); m.stop_after_all_iters_if = Some(windmill_common::flows::StopAfterIf { @@ -3402,6 +3408,7 @@ export function main(i: number) { parallel: false, parallelism: None, squash: None, + iteration_label: None, }, ); m.stop_after_all_iters_if = Some(windmill_common::flows::StopAfterIf { diff --git a/backend/tests/git_sync_pr_check_claim.rs b/backend/tests/git_sync_pr_check_claim.rs new file mode 100644 index 0000000000..a3595e70da --- /dev/null +++ b/backend/tests/git_sync_pr_check_claim.rs @@ -0,0 +1,50 @@ +//! Who checks a pull request head: the webhook receiver and the auto-pull poller +//! both claim it, and each head is checked once whichever sees it first. +#![cfg(all(feature = "enterprise", feature = "private"))] + +use sqlx::{Pool, Postgres}; +use windmill_api::git_sync_ee::{claim_pr_check_head, mark_pr_check_started}; + +const REPO: &str = "$res:u/admin/repo"; + +#[sqlx::test] +async fn a_head_is_claimed_once(db: Pool) -> anyhow::Result<()> { + sqlx::query("INSERT INTO workspace (id, name, owner) VALUES ('ws', 'ws', 'test-user')") + .execute(&db) + .await?; + let claim = |sha: &'static str, listed_at| { + let db = db.clone(); + async move { claim_pr_check_head(&db, "ws", REPO, 7, sha, listed_at, false).await } + }; + + let listed_at = Some(chrono::Utc::now() - chrono::Duration::minutes(1)); + assert!(claim("a", None).await?, "a new head is claimed"); + mark_pr_check_started(&db, "ws", REPO, 7, "a").await?; + assert!( + !claim("a", None).await?, + "the same head is not checked twice" + ); + + assert!( + !claim("b", listed_at).await?, + "a listing older than the claim cannot replace it with the head it saw" + ); + assert!(claim("b", None).await?, "a new head is claimed"); + + // Its check never started: a crash between claim and start, or an error. + assert!(!claim("b", None).await?, "not retried right away"); + sqlx::query("UPDATE git_sync_pr_check_head SET checked_at = now() - interval '11 minutes'") + .execute(&db) + .await?; + assert!(claim("b", None).await?, "retried once the delay passed"); + mark_pr_check_started(&db, "ws", REPO, 7, "b").await?; + sqlx::query("UPDATE git_sync_pr_check_head SET checked_at = now() - interval '11 minutes'") + .execute(&db) + .await?; + assert!(!claim("b", None).await?, "a started check is never retried"); + assert!( + claim_pr_check_head(&db, "ws", REPO, 7, "b", None, true).await?, + "a reopen or retarget re-runs it" + ); + Ok(()) +} diff --git a/backend/tests/hub_composed_step.rs b/backend/tests/hub_composed_step.rs new file mode 100644 index 0000000000..5943789597 --- /dev/null +++ b/backend/tests/hub_composed_step.rs @@ -0,0 +1,181 @@ +//! A builder choosing a Hub step in a flow, an agent or an app is held to the run-time rule for +//! naming a Hub path: refused without `code`, allowed with it. + +use reqwest::multipart; +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +const CODER: &str = "SECRET_TOKEN_2"; +const OP: &str = "SECRET_TOKEN_3"; +const HUB_PATH: &str = "hub/990000794/test/echo"; +const REFUSAL: &str = "Hub scripts and flows require a role that can write code"; + +fn flow(path: &str) -> Value { + json!({"modules": [{"id": "a", "value": {"type": "script", "path": path, "input_transforms": {}}}]}) +} + +#[sqlx::test(fixtures("base"))] +async fn a_hub_step_follows_the_code_capability(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + r#"UPDATE workspace_settings SET role_overrides = '{ + "operator": {"capabilities": {"flows": "compose", "apps": "compose"}}, + "developer": {"capabilities": {"flows": "compose", "apps": "compose"}} + }' WHERE workspace_id = 'test-workspace'; + UPDATE usr SET operator = true WHERE username = 'test-user-3';"#, + ) + .execute(&db) + .await?; + let server = ApiServer::start(db.clone()).await?; + let ws = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + let client = reqwest::Client::new(); + + let send = |token: &'static str, case: &'static str| { + let (ws, client) = (ws.clone(), client.clone()); + let user = if token == OP { + "test-user-3" + } else { + "test-user-2" + }; + async move { + let req = match case { + "flow create" => client.post(format!("{ws}/flows/create")).json(&json!({ + "path": format!("u/{user}/hub_step"), "summary": "", "value": flow(HUB_PATH), + })), + "flow preview" => client + .post(format!("{ws}/jobs/run/preview_flow")) + .json(&json!({ "value": flow(HUB_PATH), "args": {} })), + "agent write" => client.post(format!("{ws}/resources/create")).json(&json!({ + "path": format!("u/{user}/agent"), "resource_type": "ai_agent", + "value": {"tools": [{"id": "t", "value": {"tool_type": "flowmodule", + "type": "script", "path": HUB_PATH, "input_transforms": {}}}]}, + })), + "app create" => { + let app = json!({ + "path": format!("u/{user}/app"), "summary": "", + "value": {"files": {}, "runnables": {"a": {"name": "a", + "type": "runnableByPath", "path": HUB_PATH, "runType": "hubscript"}}}, + "policy": {"execution_mode": "publisher", "sandbox": true, + "triggerables_v2": {}}, + }); + client.post(format!("{ws}/apps/create_raw")).multipart( + multipart::Form::new() + .part( + "app", + multipart::Part::text(app.to_string()) + .mime_str("application/json") + .unwrap(), + ) + .part("js", multipart::Part::text("console.log('app')")), + ) + } + // A preset handler is allowed at run time to every role, so it is as a step. + "flow create, preset handler" => { + client.post(format!("{ws}/flows/create")).json(&json!({ + "path": format!("u/{user}/preset_step"), "summary": "", + "value": flow("hub/2431/slack/schedule-error-handler-slack"), + })) + } + _ => unreachable!(), + }; + let resp = req.bearer_auth(token).send().await.unwrap(); + (resp.status(), resp.text().await.unwrap()) + } + }; + + for case in ["flow create", "flow preview", "agent write", "app create"] { + let (status, body) = send(OP, case).await; + assert!( + status == 403 && body.contains(&format!("{HUB_PATH}: {REFUSAL}")), + "operator, {case}: {status} {body}" + ); + let (status, body) = send(CODER, case).await; + assert!(status.is_success(), "code role, {case}: {status} {body}"); + } + let (status, body) = send(OP, "flow create, preset handler").await; + assert!( + status.is_success(), + "operator, preset handler: {status} {body}" + ); + Ok(()) +} + +/// An agent save checks its Hub tools inside its transaction, so the check must not need a second +/// connection: on a one-connection pool, with the member's role never read before, the save is +/// refused rather than left waiting, from a job's token (sent first, while nothing is cached) as from +/// a personal one. Its own operator, so no other test has warmed the role cache for it; the +/// overrides match the other test's, since the workspace's roles are cached across tests. +#[sqlx::test(fixtures("base"))] +async fn a_hub_step_is_refused_on_a_one_connection_pool( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + r#"UPDATE workspace_settings SET role_overrides = '{ + "operator": {"capabilities": {"flows": "compose", "apps": "compose"}}, + "developer": {"capabilities": {"flows": "compose", "apps": "compose"}} + }' WHERE workspace_id = 'test-workspace'; + INSERT INTO password(email, password_hash, login_type, super_admin, verified, name) + VALUES ('solo@windmill.dev', 'x', 'password', false, true, 'Solo'); + INSERT INTO usr(workspace_id, email, username, is_admin, operator, role) + VALUES ('test-workspace', 'solo@windmill.dev', 'solo', false, true, 'Operator'); + INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256('SOLO_TOKEN'::bytea), 'hex'), 'SOLO_TOKEN', 'SOLO_TOKEN', + 'solo@windmill.dev', 'solo', false);"#, + ) + .execute(&db) + .await?; + let one = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .acquire_timeout(std::time::Duration::from_secs(5)) + .connect_with((*db.connect_options()).clone()) + .await?; + let server = ApiServer::start(one).await?; + set_jwt_secret().await; + let job_token = windmill_common::auth::create_jwt_token( + windmill_common::db::Authed { + email: "solo@windmill.dev".to_string(), + username: "solo".to_string(), + is_admin: false, + is_operator: true, + groups: vec![], + folders: vec![], + scopes: None, + token_prefix: None, + mcp_client: None, + capabilities: None, + }, + "test-workspace", + 3600, + None, + None, + None, + None, + ) + .await?; + for token in [job_token, "SOLO_TOKEN".to_string()] { + let resp = reqwest::Client::new() + .post(format!( + "http://localhost:{}/api/w/test-workspace/resources/create", + server.addr.port() + )) + .bearer_auth(&token) + .json(&json!({ + "path": "u/solo/agent", "resource_type": "ai_agent", + "value": {"tools": [{"id": "t", "value": {"tool_type": "flowmodule", + "type": "script", "path": HUB_PATH, "input_transforms": {}}}]}, + })) + .send() + .await?; + let (status, body) = (resp.status(), resp.text().await?); + assert!( + status == 403 && body.contains(&format!("{HUB_PATH}: {REFUSAL}")), + "{status} {body}" + ); + } + Ok(()) +} diff --git a/backend/tests/hub_named_path.rs b/backend/tests/hub_named_path.rs new file mode 100644 index 0000000000..0c432f83aa --- /dev/null +++ b/backend/tests/hub_named_path.rs @@ -0,0 +1,212 @@ +//! A Hub path named at run time is refused to a member whose role cannot write code, on every +//! route that takes one. + +use serde_json::json; +use sqlx::{Pool, Postgres}; +use windmill_common::{ + jobs::{check_can_name_runnable, RunOrigin}, + roles::RoleCapabilities, + runnable_ref::RunnableRef, +}; +use windmill_test_utils::*; + +const DEV: &str = "SECRET_TOKEN_2"; +const OP: &str = "OPERATOR_TOKEN"; +const HUB_ID: i32 = 990000792; +const REFUSAL: &str = "Hub scripts and flows require a role that can write code"; + +#[sqlx::test(fixtures("base"))] +async fn a_hub_path_named_without_code_is_refused(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 hub_path = format!("hub/{HUB_ID}/test/echo"); + + let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR; + tokio::fs::create_dir_all(hub_dir).await?; + tokio::fs::write( + format!("{hub_dir}/{HUB_ID}"), + json!({ + "content": "echo ok", "lockfile": null, "language": "bash", + "schema": {}, "summary": null, + }) + .to_string(), + ) + .await?; + + sqlx::raw_sql( + "INSERT INTO password(email, password_hash, login_type, super_admin, verified, name) + VALUES ('op@windmill.dev', 'x', 'password', false, true, 'Op'); + INSERT INTO usr(workspace_id, email, username, is_admin, operator, role) + VALUES ('test-workspace', 'op@windmill.dev', 'op', false, true, 'Operator'); + INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256('OPERATOR_TOKEN'::bytea), 'hex'), 'OPERATOR_T', 'OPERATOR_TOKEN', + 'op@windmill.dev', 'op', false); + INSERT INTO app (id, workspace_id, path, summary, policy, versions) + VALUES (999792, 'test-workspace', 'u/test-user/vapp', '', + '{\"execution_mode\": \"viewer\", \"triggerables_v2\": {}}'::jsonb, '{}');", + ) + .execute(&db) + .await?; + // What a schedule with a handler pushes for a Hub script: batch rerun reaches its path. + for (id, user) in [ + ("2aa0c0de-0000-4000-8000-000000000791", "test-user-2"), + ("2aa0c0de-0000-4000-8000-000000000792", "op"), + ] { + sqlx::query( + "INSERT INTO v2_job(id, workspace_id, kind, runnable_path, created_by, permissioned_as, + permissioned_as_email, args, raw_flow) + VALUES ($1::uuid, 'test-workspace', 'singlestepflow', $2, $3, 'u/' || $3, '', '{}', + jsonb_build_object('modules', jsonb_build_array(jsonb_build_object( + 'id', 'a', 'value', jsonb_build_object('type', 'script', 'path', $2::text)))))", + ) + .bind(id) + .bind(&hub_path) + .bind(user) + .execute(&db) + .await?; + } + + let client = reqwest::Client::new(); + let send = |token: &'static str, route: &'static str| { + let (ws, client, hub_path) = (ws.clone(), client.clone(), hub_path.clone()); + let rerun_id = if token == OP { "792" } else { "791" }; + async move { + let req = + match route { + "run/p" => client + .post(format!("{ws}/jobs/run/p/{hub_path}")) + .json(&json!({})), + "run_wait_result/p POST" => client + .post(format!("{ws}/jobs/run_wait_result/p/{hub_path}")) + .json(&json!({})), + "run_wait_result/p GET" => { + client.get(format!("{ws}/jobs/run_wait_result/p/{hub_path}")) + } + "run_and_stream/p POST" => client + .post(format!("{ws}/jobs/run_and_stream/p/{hub_path}")) + .json(&json!({})), + "run_and_stream/p GET" => { + client.get(format!("{ws}/jobs/run_and_stream/p/{hub_path}")) + } + "dynamic_select" => client + .post(format!("{ws}/jobs/run/dynamic_select")) + .json(&json!({ "entrypoint_function": "main", "runnable_ref": + { "source": "deployed", "path": hub_path, "runnable_kind": "script" } })), + "batch_rerun" => client.post(format!("{ws}/jobs/run/batch_rerun_jobs")).json( + &json!({ + "job_ids": [format!("2aa0c0de-0000-4000-8000-000000000{rerun_id}")], + "script_options_by_path": { hub_path: { "use_latest_version": true } }, + "flow_options_by_path": {}, + }), + ), + "app component" => client + .post(format!("{ws}/apps_u/execute_component/u/test-user/vapp")) + .json(&json!({ + "component": "a", "path": format!("script/{hub_path}"), "args": {} + })), + // A flow at `hub/123` has no Hub id, so only the path marks it as Hub; the + // developer gets past the check to the workspace lookup, which finds none. + "app component flow" => client + .post(format!("{ws}/apps_u/execute_component/u/test-user/vapp")) + .json(&json!({ "component": "a", "path": "flow/hub/123", "args": {} })), + _ => unreachable!(), + }; + let resp = req.bearer_auth(token).send().await.unwrap(); + let status = resp.status(); + (status, resp.text().await.unwrap()) + } + }; + + let routes = [ + "run/p", + "run_wait_result/p POST", + "run_wait_result/p GET", + "run_and_stream/p POST", + "run_and_stream/p GET", + "dynamic_select", + "batch_rerun", + "app component", + "app component flow", + ]; + in_test_worker( + &db, + async { + for route in routes { + let (status, body) = send(OP, route).await; + // Batch rerun reports every failure as the same "Couldn't re-run" line. + let refused = (status == 403 && body.contains(REFUSAL)) + || (route == "batch_rerun" && body.starts_with("Error: ")); + assert!(refused, "op on {route}: {status} {body}"); + + let (status, body) = send(DEV, route).await; + let ran = if route == "app component flow" { + status == 404 && body.contains("flow not found") + } else { + status.is_success() && !body.contains("Error") + }; + assert!(ran, "dev on {route}: {status} {body}"); + } + }, + port, + ) + .await; + + let op = windmill_api_auth::ApiAuthed { + email: "op@windmill.dev".into(), + username: "op".into(), + is_operator: true, + ..Default::default() + }; + let preset = RunnableRef::from_path("hub/2431/slack/schedule-error-handler-slack", false)?; + let origin = RunOrigin::NamedBy(op.to_authed_ref()); + check_can_name_runnable(&origin, &preset, &db, "test-workspace").await?; + Ok(()) +} + +/// The rule reads the capabilities authentication resolved and queries nothing; only a restricted +/// caller built without a role lookup reads the role, and is still refused. +#[sqlx::test(fixtures("base"))] +async fn the_rule_reads_code_from_the_caller(db: Pool) -> anyhow::Result<()> { + sqlx::raw_sql( + "INSERT INTO usr(workspace_id, email, username, is_admin, operator, role) + VALUES ('test-workspace', 'op@windmill.dev', 'op', false, true, 'Operator');", + ) + .execute(&db) + .await?; + let hub = RunnableRef::from_path(&format!("hub/{HUB_ID}/test/echo"), false)?; + let op = |capabilities| windmill_api_auth::ApiAuthed { + email: "op@windmill.dev".into(), + username: "op".into(), + is_operator: true, + capabilities, + ..Default::default() + }; + let check = |authed: windmill_api_auth::ApiAuthed, db: Pool| { + let hub = hub.clone(); + async move { + let origin = RunOrigin::NamedBy(authed.to_authed_ref()); + check_can_name_runnable(&origin, &hub, &db, "test-workspace").await + } + }; + + let unresolved = check(op(None), db.clone()).await; + assert!( + matches!(&unresolved, Err(e) if e.to_string().contains(REFUSAL)), + "{unresolved:?}" + ); + + // Any query on this pool fails. + let dead = sqlx::postgres::PgPoolOptions::new() + .acquire_timeout(std::time::Duration::from_millis(200)) + .connect_lazy("postgres://nobody@127.0.0.1:1/none")?; + let refused = check(op(Some(RoleCapabilities::OPERATOR)), dead.clone()).await; + assert!( + matches!(&refused, Err(e) if e.to_string().contains(REFUSAL)), + "{refused:?}" + ); + let coder = RoleCapabilities { code: true, ..RoleCapabilities::OPERATOR }; + check(op(Some(coder)), dead).await?; + Ok(()) +} diff --git a/backend/tests/hub_saved_path.rs b/backend/tests/hub_saved_path.rs new file mode 100644 index 0000000000..a83b1bf287 --- /dev/null +++ b/backend/tests/hub_saved_path.rs @@ -0,0 +1,251 @@ +//! A Hub path saved into a trigger or a schedule is checked when it is chosen, against the member +//! saving it: refused without `code`, and only on the paths the save changes. + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +const DEV: &str = "SECRET_TOKEN_2"; +const OP: &str = "OPERATOR_TOKEN"; +const HUB: &str = "hub/990000802/test/echo"; +const OTHER_HUB: &str = "hub/990000803/test/echo"; +const PRESET: &str = "hub/2431/slack/schedule-error-handler-slack"; +const REFUSAL: &str = "Hub scripts and flows require a role that can write code"; + +#[cfg(feature = "http_trigger")] +fn http(path: &str, script_path: &str, error_handler: Option<&str>) -> Value { + json!({ + "path": path, "script_path": script_path, "is_flow": false, "mode": "disabled", + "route_path": path.replace('/', "_"), "request_type": "async", + "authentication_method": "none", "http_method": "post", "is_static_website": false, + "workspaced_route": true, "wrap_body": false, "raw_string": false, + "error_handler_path": error_handler, + }) +} + +#[cfg(feature = "websocket")] +fn websocket(path: &str, url: &str, initial: Option<&str>) -> Value { + json!({ + "path": path, "script_path": "f/shared/s", "is_flow": false, "mode": "disabled", + "url": url, "filters": [], "can_return_message": false, "can_return_error_result": false, + "initial_messages": initial.map(|p| + json!([{"runnable_result": {"path": p, "args": {}, "is_flow": false}}])), + }) +} + +fn schedule(path: &str, script_path: &str, on_failure: Option<&str>) -> Value { + json!({ + "path": path, "schedule": "0 0 0 * * *", "timezone": "UTC", "script_path": script_path, + "is_flow": false, "enabled": false, "on_failure": on_failure, + }) +} + +#[sqlx::test(fixtures("base"))] +async fn a_saved_hub_path_follows_the_code_capability(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + r#"INSERT INTO password(email, password_hash, login_type, super_admin, verified, name) + VALUES ('op@windmill.dev', 'x', 'password', false, true, 'Op'); + INSERT INTO usr(workspace_id, email, username, is_admin, operator, role) + VALUES ('test-workspace', 'op@windmill.dev', 'op', false, true, 'Operator'); + INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256('OPERATOR_TOKEN'::bytea), 'hex'), 'OPERATOR_T', + 'OPERATOR_TOKEN', 'op@windmill.dev', 'op', false); + INSERT INTO folder(workspace_id, name, display_name, owners, extra_perms) + VALUES ('test-workspace', 'shared', 'shared', '{}', + '{"u/op": true, "u/test-user-2": true}');"#, + ) + .execute(&db) + .await?; + let server = ApiServer::start(db.clone()).await?; + let ws = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + let client = reqwest::Client::new(); + let send = async |token: &str, route: &str, body: Value| { + let resp = client + .post(format!("{ws}/{route}")) + .bearer_auth(token) + .json(&body) + .send() + .await + .unwrap(); + (resp.status().as_u16(), resp.text().await.unwrap()) + }; + + // Rows a developer saved, for an operator to edit. + #[cfg(feature = "websocket")] + { + let ws = websocket( + "f/shared/dev_ws", + &format!("$script:{HUB}"), + Some(OTHER_HUB), + ); + let (s, b) = send(DEV, "websocket_triggers/create", ws).await; + assert_eq!(s, 201, "{b}"); + } + #[cfg(feature = "http_trigger")] + { + let (s, b) = send( + DEV, + "http_triggers/create", + http("f/shared/dev_route", HUB, None), + ) + .await; + assert_eq!(s, 201, "{b}"); + } + for path in ["f/shared/dev_sched", "f/shared/plain_sched"] { + let on_failure = (path == "f/shared/dev_sched").then(|| format!("script/{HUB}")); + let (s, b) = send( + DEV, + "schedules/create", + schedule(path, "f/shared/s", on_failure.as_deref()), + ) + .await; + assert!(s < 300, "{b}"); + } + let edit = |on_failure: &str| { + json!({"schedule": "0 0 1 * * *", "timezone": "UTC", + "on_failure": format!("script/{on_failure}")}) + }; + + // (case, route, body for a path): refused to the operator. + #[allow(unused_mut)] + let mut refused: Vec<(&str, String, Box Value>)> = vec![ + ( + "schedule create, Hub target", + "schedules/create".into(), + Box::new(|p| schedule(p, HUB, None)), + ), + ( + "schedule create, Hub on_failure", + "schedules/create".into(), + Box::new(|p| schedule(p, "f/shared/s", Some(&format!("script/{HUB}")))), + ), + ( + "schedule edit, adding a Hub on_failure", + "schedules/update/f/shared/plain_sched".into(), + Box::new(|_| edit(HUB)), + ), + ]; + #[cfg(feature = "http_trigger")] + refused.extend([ + ( + "HTTP create, Hub target", + "http_triggers/create".into(), + Box::new(|p: &str| http(p, HUB, None)) as Box Value>, + ), + ( + "HTTP create, Hub error handler", + "http_triggers/create".into(), + Box::new(|p: &str| http(p, "f/shared/s", Some(HUB))), + ), + ( + "HTTP bulk create, Hub target", + "http_triggers/create_many".into(), + Box::new(|p: &str| { + json!([ + http(&format!("{p}_a"), "f/shared/s", None), + http(p, HUB, None) + ]) + }), + ), + ]); + #[cfg(feature = "websocket")] + refused.extend([ + ( + "WebSocket create, Hub URL", + "websocket_triggers/create".into(), + Box::new(|p: &str| websocket(p, &format!("$script:{HUB}"), None)) + as Box Value>, + ), + ( + "WebSocket create, Hub initial message", + "websocket_triggers/create".into(), + Box::new(|p: &str| websocket(p, "$flow:f/shared/url", Some(HUB))), + ), + ( + "WebSocket capture config, Hub URL", + "capture/set_config".into(), + Box::new(|p: &str| { + json!({"trigger_kind": "websocket", "path": p, "is_flow": false, + "trigger_config": {"url": format!("$script:{HUB}")}}) + }), + ), + ]); + + for (i, (case, route, body)) in refused.iter().enumerate() { + let (status, text) = send(OP, route, body(&format!("f/shared/op_{i}"))).await; + assert!( + status == 403 && text.contains(&format!("{HUB}: {REFUSAL}")), + "operator, {case}: {status} {text}" + ); + } + let (case, route, body) = &refused[0]; + let (status, text) = send(DEV, route, body("f/shared/dev_0")).await; + assert!(status < 300, "developer, {case}: {status} {text}"); + #[cfg(feature = "http_trigger")] + { + let written: i64 = + sqlx::query_scalar("SELECT count(*) FROM http_trigger WHERE path LIKE 'f/shared/op_%'") + .fetch_one(&db) + .await?; + assert_eq!(written, 0, "a refused save wrote a row"); + } + + // Allowed to the operator: what the row already holds, and a preset handler. + #[allow(unused_mut)] + let mut allowed: Vec<(&str, &str, Value)> = vec![ + ( + "schedule edit, Hub on_failure unchanged", + "schedules/update/f/shared/dev_sched", + edit(HUB), + ), + ( + "schedule create, preset on_failure", + "schedules/create", + schedule( + "f/shared/op_preset", + "f/shared/s", + Some(&format!("script/{PRESET}")), + ), + ), + ]; + #[cfg(feature = "http_trigger")] + allowed.push(( + "HTTP update, Hub target unchanged, renamed", + "http_triggers/update/f/shared/dev_route", + http("f/shared/dev_route_renamed", HUB, None), + )); + #[cfg(feature = "websocket")] + allowed.push(( + "WebSocket update, Hub URL and initial message unchanged, renamed", + "websocket_triggers/update/f/shared/dev_ws", + websocket( + "f/shared/dev_ws_renamed", + &format!("$script:{HUB}"), + Some(OTHER_HUB), + ), + )); + for (case, route, body) in allowed { + let (status, text) = send(OP, route, body).await; + assert!(status < 300, "operator, {case}: {status} {text}"); + } + + #[cfg(feature = "http_trigger")] + { + let case = "HTTP update to a different Hub target"; + let (status, text) = send( + OP, + "http_triggers/update/f/shared/dev_route_renamed", + http("f/shared/dev_route_renamed", OTHER_HUB, None), + ) + .await; + assert!( + status == 403 && text.contains(&format!("{OTHER_HUB}: {REFUSAL}")), + "operator, {case}: {status} {text}" + ); + } + Ok(()) +} diff --git a/backend/tests/inline_preview_auth.rs b/backend/tests/inline_preview_auth.rs index ec7042a4af..4fdb5b77b5 100644 --- a/backend/tests/inline_preview_auth.rs +++ b/backend/tests/inline_preview_auth.rs @@ -78,6 +78,7 @@ async fn operator_job_token(job_id: uuid::Uuid) -> String { scopes: None, token_prefix: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::NONE), }; create_jwt_token( authed, diff --git a/backend/tests/job_path_access.rs b/backend/tests/job_path_access.rs new file mode 100644 index 0000000000..c72c2e98a6 --- /dev/null +++ b/backend/tests/job_path_access.rs @@ -0,0 +1,109 @@ +//! Job routes that act on a script or flow path rather than a job id must hold the caller to +//! the access the path's own routes require: `queue/cancel_persistent` to the per-job cancel +//! check, `run/flow_dependencies` to write access on the flow path. + +use sqlx::{Pool, Postgres}; +use uuid::Uuid; +use windmill_test_utils::*; + +const W_ID: &str = "test-workspace"; + +async fn post_json( + url: &str, + token: &str, + body: serde_json::Value, +) -> (reqwest::StatusCode, String) { + let resp = reqwest::Client::new() + .post(url) + .header("Authorization", format!("Bearer {token}")) + .json(&body) + .send() + .await + .expect("request"); + let status = resp.status(); + (status, resp.text().await.expect("body")) +} + +#[sqlx::test(fixtures("base"))] +async fn cancel_persistent_requires_cancel_access(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let path = "u/test-user-2/loop"; + sqlx::query( + "INSERT INTO script (workspace_id, hash, path, summary, description, content, created_by, \ + language, lock, restart_unless_cancelled) \ + VALUES ($1, 1, $2, '', '', 'echo', 'test-user-2', 'bash', '', true)", + ) + .bind(W_ID) + .bind(path) + .execute(&db) + .await?; + let id = Uuid::new_v4(); + sqlx::query( + "INSERT INTO v2_job (id, workspace_id, created_by, created_at, permissioned_as, \ + permissioned_as_email, kind, runnable_id, runnable_path, script_lang, tag, \ + visible_to_owner) \ + VALUES ($1, $2, 'test-user-2', now(), 'u/test-user-2', 'test2@windmill.dev', 'script', \ + 1, $3, 'bash', 'bash', true)", + ) + .bind(id) + .bind(W_ID) + .bind(path) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, running, started_at, tag) \ + VALUES ($1, $2, now(), true, now(), 'bash')", + ) + .bind(id) + .bind(W_ID) + .execute(&db) + .await?; + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let (status, body) = post_json( + &format!("http://localhost:{port}/api/w/{W_ID}/jobs_u/queue/cancel_persistent/{path}"), + "SECRET_TOKEN_3", + serde_json::json!({}), + ) + .await; + assert_eq!( + status, + reqwest::StatusCode::FORBIDDEN, + "a member who cannot see the run must not cancel it: {body}" + ); + let canceled_by: Option = + sqlx::query_scalar("SELECT canceled_by FROM v2_job_queue WHERE id = $1") + .bind(id) + .fetch_one(&db) + .await?; + assert_eq!(canceled_by, None, "the perpetual run is left running"); + Ok(()) +} + +#[sqlx::test(fixtures("base"))] +async fn flow_dependencies_requires_write_on_the_path(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let (status, body) = post_json( + &format!("http://localhost:{port}/api/w/{W_ID}/jobs/run/flow_dependencies_async"), + "SECRET_TOKEN_3", + serde_json::json!({ "path": "u/test-user-2/flow", "flow_value": { "modules": [] } }), + ) + .await; + assert_eq!( + status, + reqwest::StatusCode::FORBIDDEN, + "a developer must not run a dependency job for a flow path they cannot write: {body}" + ); + let queued: i64 = sqlx::query_scalar( + "SELECT count(*) FROM v2_job WHERE workspace_id = $1 AND runnable_path = $2", + ) + .bind(W_ID) + .bind("u/test-user-2/flow") + .fetch_one(&db) + .await?; + assert_eq!(queued, 0, "no dependency job is queued"); + Ok(()) +} diff --git a/backend/tests/leave_instance_tokens.rs b/backend/tests/leave_instance_tokens.rs new file mode 100644 index 0000000000..7697eebb90 --- /dev/null +++ b/backend/tests/leave_instance_tokens.rs @@ -0,0 +1,45 @@ +//! Leaving the instance ends every credential of the account, as deleting it does: a token kept +//! past the leave would authenticate as whoever later takes the address. + +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base"))] +async fn test_leave_instance_deletes_tokens(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base = format!("http://localhost:{}/api/users", server.addr.port()); + let client = reqwest::Client::new(); + + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256('OTHER_TOKEN_2'::bytea), 'hex'), 'OTHER_TOKE', 'OTHER_TOKEN_2', + 'test2@windmill.dev', 'api', false)", + ) + .execute(&db) + .await?; + + let resp = client + .post(format!("{base}/leave_instance")) + .bearer_auth("SECRET_TOKEN_2") + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let left: i64 = + sqlx::query_scalar("SELECT count(*) FROM token WHERE email = 'test2@windmill.dev'") + .fetch_one(&db) + .await?; + assert_eq!(left, 0, "tokens of the account survived the leave"); + + let whoami = |token: &'static str| { + client + .get(format!("{base}/whoami")) + .bearer_auth(token) + .send() + }; + assert_eq!(whoami("OTHER_TOKEN_2").await?.status(), 401); + assert_eq!(whoami("SECRET_TOKEN_3").await?.status(), 200); + Ok(()) +} diff --git a/backend/tests/mcp_list_run_gated.rs b/backend/tests/mcp_list_run_gated.rs new file mode 100644 index 0000000000..9f0b889a05 --- /dev/null +++ b/backend/tests/mcp_list_run_gated.rs @@ -0,0 +1,145 @@ +//! A role that cannot run is offered no run tool over MCP, and a run it calls stays refused: +//! through a token scoped to a selection of scripts, and through a full session token. +#![cfg(feature = "mcp")] + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +async fn mcp( + port: u16, + path: &str, + token: &str, + method: &str, + params: Value, +) -> anyhow::Result { + let body = reqwest::Client::new() + .post(format!("http://localhost:{port}{path}")) + .bearer_auth(token) + .header("accept", "application/json, text/event-stream") + .header("mcp-protocol-version", "2025-06-18") + .json(&json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})) + .send() + .await? + .text() + .await?; + let data = body + .lines() + .find_map(|l| l.strip_prefix("data: ")) + .unwrap_or(&body); + Ok(serde_json::from_str(data)?) +} + +#[sqlx::test(fixtures("base"))] +async fn test_view_only_role_lists_no_runnable_tools(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + "INSERT INTO script (workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) + VALUES ('test-workspace', 'test-user-3', 'export function main() { return 1 }', '{}', '', '', 'u/test-user-3/hello', 7788201, 'bun', ''); + INSERT INTO token (token_hash, token_prefix, email, label, super_admin, scopes, workspace_id) + VALUES (encode(sha256('SCOPED_MCP_TOKEN'::bytea), 'hex'), 'SCOPED_MCP', 'test3@windmill.dev', 'mcp', false, + ARRAY['mcp:scripts:u/test-user-3/hello'], 'test-workspace'), + (encode(sha256('ADMIN_MCP_TOKEN'::bytea), 'hex'), 'ADMIN_MCP_', 'test@windmill.dev', 'mcp', false, + ARRAY['mcp:scripts:u/test-user-3/hello'], 'test-workspace'), + (encode(sha256('FULL_MCP_TOKEN'::bytea), 'hex'), 'FULL_MCP_T', 'test3@windmill.dev', 'mcp', false, + ARRAY['mcp:all'], 'test-workspace'), + (encode(sha256('ADMIN_FULL_MCP_TOKEN'::bytea), 'hex'), 'ADMIN_FULL', 'test@windmill.dev', 'mcp', false, + ARRAY['mcp:all'], 'test-workspace'); + UPDATE workspace_settings SET role_overrides = '{\"developer\": {\"capabilities\": {\"run\": false}}}' + WHERE workspace_id = 'test-workspace';", + ) + .execute(&db) + .await?; + windmill_common::roles::invalidate_workspace_roles_cache("test-workspace"); + + let server = ApiServer::start_mcp(db.clone()).await?; + let port = server.addr.port(); + const SELECTION: &str = "/api/mcp/w/test-workspace/mcp"; + const SESSION: &str = "/api/mcp"; + + let admin = mcp(port, SELECTION, "ADMIN_MCP_TOKEN", "tools/list", json!({})).await?; + assert!( + admin["result"]["tools"] + .as_array() + .is_some_and(|t| t.iter().any(|t| t["name"] == "hello")), + "a role that can run must still list the tool: {admin}" + ); + + let list = mcp(port, SELECTION, "SCOPED_MCP_TOKEN", "tools/list", json!({})).await?; + let tools = list["result"]["tools"] + .as_array() + .unwrap_or_else(|| panic!("no tools in {list}")); + assert!( + tools.is_empty(), + "view-only role must list no run tool: {list}" + ); + + let call = mcp( + port, + SELECTION, + "SCOPED_MCP_TOKEN", + "tools/call", + json!({"name": "hello", "arguments": {}}), + ) + .await?; + let msg = call["error"]["message"].as_str().unwrap_or_default(); + assert!( + msg.contains("Your role cannot run"), + "call must stay refused: {call}" + ); + + let names = |list: &Value| -> Vec { + list["result"]["tools"] + .as_array() + .unwrap_or_else(|| panic!("no tools in {list}")) + .iter() + .filter_map(|t| t["name"].as_str().map(str::to_string)) + .collect() + }; + let admin = names( + &mcp( + port, + SESSION, + "ADMIN_FULL_MCP_TOKEN", + "tools/list", + json!({}), + ) + .await?, + ); + assert!(admin.iter().any(|n| n == "run_script"), "{admin:?}"); + + let session = names(&mcp(port, SESSION, "FULL_MCP_TOKEN", "tools/list", json!({})).await?); + assert!( + session.iter().any(|n| n == "list_workspace_items") + && !session + .iter() + .any(|n| n.starts_with("run_") || n.starts_with("test_run_")), + "view-only role must get the read-only toolset: {session:?}" + ); + + let init = mcp( + port, + SESSION, + "FULL_MCP_TOKEN", + "initialize", + json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "t", "version": "0"}}), + ) + .await?; + let instructions = init["result"]["instructions"].as_str().unwrap_or_default(); + assert!( + instructions.contains("This connection is read-only"), + "view-only role must read the read_only instructions: {init}" + ); + + let run = mcp( + port, + SESSION, + "FULL_MCP_TOKEN", + "tools/call", + json!({"name": "run_script", "arguments": {"workspace_id": "test-workspace", "path": "u/test-user-3/hello", "args": {}}}), + ) + .await?; + let msg = run["error"]["message"].as_str().unwrap_or_default(); + assert!(msg.contains("read-only"), "run must stay refused: {run}"); + Ok(()) +} diff --git a/backend/tests/mcp_runnable_tool_failure.rs b/backend/tests/mcp_runnable_tool_failure.rs new file mode 100644 index 0000000000..5f27c82c29 --- /dev/null +++ b/backend/tests/mcp_runnable_tool_failure.rs @@ -0,0 +1,107 @@ +//! A script tool on a selection-scoped MCP token reports a run that failed as a tool execution +//! error (`isError`) naming the run, and a run that succeeded as its result. +#![cfg(feature = "mcp")] + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +async fn seed(db: &Pool) -> anyhow::Result<()> { + for (hash, path, content) in [ + ( + 7000001_i64, + "u/test-user/fails", + "echo about to fail\nexit 3", + ), + (7000002_i64, "u/test-user/works", "echo all good"), + ] { + sqlx::query( + "INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, + schema, summary, description, lock) + VALUES ('test-workspace', $1, $2, $3, 'bash', 'script', 'test-user', + '{\"type\": \"object\", \"properties\": {}}', '', '', '')", + ) + .bind(hash) + .bind(path) + .bind(content) + .execute(db) + .await?; + } + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, token, email, label, workspace_id, scopes) + VALUES (encode(sha256('MCP_SELECTION'::bytea), 'hex'), 'MCP_SELECT', 'MCP_SELECTION', + 'test@windmill.dev', 'mcp', 'test-workspace', + ARRAY['mcp:scripts:u/test-user/fails,u/test-user/works'])", + ) + .execute(db) + .await?; + Ok(()) +} + +async fn rpc(base: &str, method: &str, params: Value) -> anyhow::Result { + let body = reqwest::Client::new() + .post(format!("{base}/api/mcp/w/test-workspace/mcp")) + .bearer_auth("MCP_SELECTION") + .header("Accept", "application/json, text/event-stream") + .json(&json!({ "jsonrpc": "2.0", "id": 1, "method": method, "params": params })) + .send() + .await? + .text() + .await?; + let data = body + .lines() + .filter_map(|l| l.strip_prefix("data:")) + .find(|l| !l.trim().is_empty()) + .unwrap_or(&body); + Ok(serde_json::from_str(data.trim())?) +} + +async fn call(base: &str, tools: &[Value], path_suffix: &str) -> anyhow::Result { + let name = tools + .iter() + .filter_map(|t| t["name"].as_str()) + .find(|n| n.ends_with(path_suffix)) + .unwrap_or_else(|| panic!("no tool for {path_suffix} in {tools:?}")); + let res = rpc(base, "tools/call", json!({ "name": name, "arguments": {} })).await?; + Ok(res["result"].clone()) +} + +#[sqlx::test(fixtures("base"))] +async fn test_failed_run_is_a_tool_error(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + seed(&db).await?; + let server = ApiServer::start_mcp(db.clone()).await?; + let port = server.addr.port(); + let base = format!("http://localhost:{port}"); + + in_test_worker( + &db, + async { + let tools = rpc(&base, "tools/list", json!({})).await?; + let tools = tools["result"]["tools"] + .as_array() + .cloned() + .unwrap_or_default(); + + let failed = call(&base, &tools, "fails").await?; + assert_eq!(failed["isError"], json!(true), "{failed}"); + let text = failed["content"][0]["text"].as_str().unwrap_or_default(); + assert!(text.contains("exit code"), "{text}"); + let job_id: String = sqlx::query_scalar( + "SELECT id::text FROM v2_job WHERE runnable_path = 'u/test-user/fails'", + ) + .fetch_one(&db) + .await?; + assert!(text.contains(&job_id), "{text}"); + + let ok = call(&base, &tools, "works").await?; + assert_ne!(ok["isError"], json!(true), "{ok}"); + let text = ok["content"][0]["text"].as_str().unwrap_or_default(); + assert_eq!(text, "\"all good\""); + anyhow::Ok(()) + }, + port, + ) + .await?; + Ok(()) +} diff --git a/backend/tests/pool_hold_and_wait.rs b/backend/tests/pool_hold_and_wait.rs index 44af05ab39..4f05c3adb4 100644 --- a/backend/tests/pool_hold_and_wait.rs +++ b/backend/tests/pool_hold_and_wait.rs @@ -38,6 +38,7 @@ async fn run_by_path_of_a_missing_script_uses_one_connection(db: Pool) folders: &folders, scopes: &None, token_prefix: &None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), }; let lookup = windmill_common::get_latest_deployed_hash_for_path( Some(UserDbWithAuthed { authed: &authed, db: UserDB::new(one.clone()) }), diff --git a/backend/tests/postgres_trigger_scope.rs b/backend/tests/postgres_trigger_scope.rs index 7171812fa9..9e7d8a665b 100644 --- a/backend/tests/postgres_trigger_scope.rs +++ b/backend/tests/postgres_trigger_scope.rs @@ -27,6 +27,7 @@ fn scoped_authed(scopes: Vec<&str>) -> ApiAuthed { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/tests/python_jobs.rs b/backend/tests/python_jobs.rs index 4236599aba..0eb6b47cdf 100644 --- a/backend/tests/python_jobs.rs +++ b/backend/tests/python_jobs.rs @@ -51,7 +51,7 @@ mod dedicated_worker_protocol_python { fn run_py_multi_script_test( scripts: &[(&str, &str)], jobs: Vec, - ) -> Vec> { + ) -> Vec> { let temp_dir = tempfile::tempdir().unwrap(); create_py_worker_files(temp_dir.path(), scripts); @@ -87,13 +87,7 @@ mod dedicated_worker_protocol_python { match parse_dedicated_worker_line(response.trim()) { DedicatedWorkerResult::Success(value) => results.push(Ok(value)), - DedicatedWorkerResult::Error(err) => { - let msg = err["message"] - .as_str() - .unwrap_or("Unknown error") - .to_string(); - results.push(Err(msg)); - } + DedicatedWorkerResult::Error(err) => results.push(Err(err)), other => panic!("Unexpected response: {:?}", other), } } @@ -108,7 +102,7 @@ mod dedicated_worker_protocol_python { script_path: &str, content: &str, jobs: Vec, - ) -> Vec> { + ) -> Vec> { run_py_multi_script_test( &[(script_path, content)], jobs.into_iter() @@ -180,7 +174,10 @@ mod dedicated_worker_protocol_python { let results = run_py_multi_script_test( &[ ("f/ok", "def main(x: int):\n return x * 2\n"), - ("f/err", "def main(msg: str):\n raise Exception(msg)\n"), + ( + "f/err", + "def main(msg: str):\n e = Exception(msg)\n e.status_code = 429\n e.info = {}\n e.info['self'] = e.info\n raise e\n", + ), ], vec![ MultiScriptJob { @@ -199,8 +196,12 @@ mod dedicated_worker_protocol_python { ); assert_eq!(results.len(), 3); assert_eq!(results[0], Ok(serde_json::json!(10))); - assert!(results[1].is_err()); - assert_eq!(results[1], Err("boom".to_string())); + let err = results[1].as_ref().unwrap_err(); + assert_eq!(err["message"], "boom"); + assert_eq!( + err["extra"], + serde_json::json!({ "status_code": 429, "info": "[unserializable]" }) + ); assert_eq!(results[2], Ok(serde_json::json!(20))); } @@ -214,10 +215,9 @@ mod dedicated_worker_protocol_python { }], ); assert_eq!(results.len(), 1); - assert!(results[0].is_err()); - assert!(results[0] - .as_ref() - .unwrap_err() + assert!(results[0].as_ref().unwrap_err()["message"] + .as_str() + .unwrap() .contains("Script not found")); } @@ -1141,9 +1141,9 @@ async fn test_relative_imports_python(db: Pool) -> anyhow::Result<()> let content = r#" from f.system.same_folder_script import main as test1 from .same_folder_script import main as test2 -from f.system_relative.different_folder_script import main as test3 -from ..system_relative.different_folder_script import main as test4 - +from f.system_relative.system import main as test3 +from ..system_relative.loader import main as test4 + def main(): return [test1(), test2(), test3(), test4()] "# diff --git a/backend/tests/reserved_control_args.rs b/backend/tests/reserved_control_args.rs index 5fb7fd4b3a..ed0fa6d002 100644 --- a/backend/tests/reserved_control_args.rs +++ b/backend/tests/reserved_control_args.rs @@ -91,6 +91,7 @@ fn trigger_authed() -> windmill_api_auth::ApiAuthed { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } @@ -125,6 +126,7 @@ async fn trigger_args_lose_every_reserved_control_key(db: Pool) -> any None, None, trigger_authed(), + windmill_common::jobs::ChosenBy::Deployed, "test-workspace", &windmill_common::runnable_ref::RunnableRef::from_path(SCRIPT_PATH, false)?, args, diff --git a/backend/tests/runnables_list_pagination.rs b/backend/tests/runnables_list_pagination.rs index 663bd6c080..f0bcec9423 100644 --- a/backend/tests/runnables_list_pagination.rs +++ b/backend/tests/runnables_list_pagination.rs @@ -395,6 +395,18 @@ async fn test_runnables_search_and_kind_filters(db: Pool) -> anyhow::R assert!(none.is_empty(), "{query} must match nothing, got {none:?}"); } + // `search_any_order` drops the order, never the requirement that every term appears. + assert_eq!( + list_once(port, "search=one%20deploy&search_any_order=true").await, + vec!["script:f/alpha/one".to_string()], + "any order matches terms given out of order" + ); + let none = list_once(port, "search=deploy%20beta&search_any_order=true").await; + assert!( + none.is_empty(), + "every term must still appear, got {none:?}" + ); + // kinds filter selects a single kind. let flows = list_once(port, "kinds=flow").await; assert_eq!(flows, vec!["flow:f/alpha/flowy".to_string()], "kinds=flow"); @@ -445,6 +457,25 @@ async fn test_runnables_search_and_kind_filters(db: Pool) -> anyhow::R by_storage_path.is_empty(), "the draft_ path is not searchable, got {by_storage_path:?}" ); + + // Words in any script reach the any-order search; the ordered one keeps the homepage's + // ASCII rule and matches nothing. + let r = authed( + client().post(format!("{base}/scripts/create")), + "SECRET_TOKEN", + ) + .json(&new_script("f/beta/weather", "获取城市天气")) + .send() + .await?; + assert_eq!(r.status(), 201, "create script: {}", r.text().await?); + assert_eq!( + list_once(port, "search=%E5%A4%A9%E6%B0%94&search_any_order=true").await, + vec!["script:f/beta/weather".to_string()], + "a non-ASCII word matches in any order" + ); + assert!(list_once(port, "search=%E5%A4%A9%E6%B0%94") + .await + .is_empty()); Ok(()) } diff --git a/backend/tests/runnables_list_paths.rs b/backend/tests/runnables_list_paths.rs new file mode 100644 index 0000000000..abbd34e5f7 --- /dev/null +++ b/backend/tests/runnables_list_paths.rs @@ -0,0 +1,78 @@ +//! `GET /w/{workspace}/runnables/list?paths=`: only rows at the given paths, each kind on its +//! own at a shared path, archived rows left out. + +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +async fn insert_script( + db: &Pool, + hash: i64, + path: &str, + archived: bool, +) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO script (workspace_id, hash, path, summary, description, content, created_by, language, archived) + VALUES ('test-workspace', $1, $2, '', '', 'x', 'test-user', 'deno', $3)", + ) + .bind(hash) + .bind(path) + .bind(archived) + .execute(db) + .await?; + Ok(()) +} + +async fn insert_flow(db: &Pool, path: &str, archived: bool) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO flow (workspace_id, path, summary, description, value, edited_by, schema, archived) + VALUES ('test-workspace', $1, '', '', '{}'::jsonb, 'test-user', '{}'::json, $2)", + ) + .bind(path) + .bind(archived) + .execute(db) + .await?; + Ok(()) +} + +#[sqlx::test(fixtures("base"))] +async fn test_list_runnables_by_paths(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + // A renamed script leaves its archived versions behind; a flow can then take the path. + insert_script(&db, 9100001, "u/test-user/moved", true).await?; + insert_flow(&db, "u/test-user/moved", false).await?; + insert_script(&db, 9100002, "u/test-user/live", false).await?; + insert_flow(&db, "u/test-user/archived_flow", true).await?; + insert_script(&db, 9100003, "u/test-user/not_asked", false).await?; + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let body: serde_json::Value = reqwest::Client::new() + .get(format!( + "http://localhost:{port}/api/w/test-workspace/runnables/list\ + ?paths=u/test-user/moved,u/test-user/live,u/test-user/archived_flow,u/test-user/gone" + )) + .header("Authorization", "Bearer SECRET_TOKEN") + .send() + .await? + .error_for_status()? + .json() + .await?; + let mut found: Vec = body["items"] + .as_array() + .unwrap() + .iter() + .map(|x| { + format!( + "{}:{}", + x["type"].as_str().unwrap(), + x["path"].as_str().unwrap() + ) + }) + .collect(); + found.sort(); + assert_eq!(found, ["flow:u/test-user/moved", "script:u/test-user/live"]); + + Ok(()) +} diff --git a/backend/tests/suspend_resume.rs b/backend/tests/suspend_resume.rs index 0decc16519..c18880dbcc 100644 --- a/backend/tests/suspend_resume.rs +++ b/backend/tests/suspend_resume.rs @@ -317,6 +317,76 @@ mod suspend_resume { Ok(()) } + /// A rejection is audited once, under the approver, by the API. The worker's own row is + /// for a timeout, which no one else records. + #[cfg(all(feature = "deno_core", feature = "enterprise", feature = "private"))] + #[sqlx::test(fixtures("base"))] + async fn rejected_suspend_that_continues_is_audited_once( + db: Pool, + ) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let value: FlowValue = serde_json::from_value(json!({ + "modules": [{ + "id": "a", + "value": { + "input_transforms": { + "port": { "type": "javascript", "expr": "flow_input.port" }, + }, + "type": "rawscript", + "language": "bun", + "content": "\ + export async function main(port) {\ + 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}` } }\ + )).text();\ + await fetch(\ + `http://localhost:${port}/api/w/test-workspace/jobs_u/cancel/${job}/0/${secret}?approver=ruben`,\ + { method: 'POST', body: JSON.stringify('from job'), headers: { 'content-type': 'application/json' } }\ + );\ + return 'a ran';\ + }", + }, + "suspend": { "required_events": 1, "continue_on_disapprove_timeout": true }, + }, { + "id": "b", + "value": { + "input_transforms": {}, + "type": "rawscript", + "language": "bun", + "content": "export function main() { return 'b ran' }", + }, + }], + }))?; + + let completed = + RunJob::from(JobPayload::RawFlow { value, path: None, restarted_from: None }) + .arg("port", json!(port)) + .run_until_complete(&db, false, port) + .await; + + server.close().await.unwrap(); + + assert_eq!(json!("b ran"), completed.json_result().unwrap()); + + let rows: Vec<(String, Option)> = sqlx::query_as( + "SELECT username, parameters->>'approved' FROM audit_partitioned + WHERE operation = 'jobs.suspend_resume' AND parameters->>'job_id' = $1", + ) + .bind(completed.id.to_string()) + .fetch_all(&db) + .await?; + assert_eq!(vec![("ruben".to_string(), Some("false".to_string()))], rows); + + Ok(()) + } + /// Test that self-approval is blocked when self_approval_disabled is true. /// /// This test verifies that when a flow has an approval step with self_approval_disabled=true, diff --git a/backend/tests/suspended_pull_index.rs b/backend/tests/suspended_pull_index.rs index 4b31f4d45e..c1e81009fe 100644 --- a/backend/tests/suspended_pull_index.rs +++ b/backend/tests/suspended_pull_index.rs @@ -5,7 +5,7 @@ use serde_json::Value; use sqlx::{Pool, Postgres}; -use windmill_common::worker::make_suspended_pull_query; +use windmill_common::worker::{make_suspended_pull_query, make_suspended_pull_query_fairness}; /// Depth-first walk of an `EXPLAIN (FORMAT JSON)` plan tree. fn nodes(plan: &Value, out: &mut Vec) { @@ -39,19 +39,34 @@ async fn suspended_pull_tests_resume_time_inside_the_index( let version: String = sqlx::query_scalar("SELECT version()") .fetch_one(&mut *conn) .await?; + let tags = ["flow".to_string()]; // FORMAT JSON rather than the default: `Index Cond` and `Filter` are separate keys on the // node, so this does not ride on EXPLAIN's line layout staying put across a major bump. - let explained: Value = sqlx::query_scalar(&format!( + let plain: Value = sqlx::query_scalar(&format!( "EXPLAIN (FORMAT JSON) {}", - make_suspended_pull_query(&["flow".to_string()]) + make_suspended_pull_query(&tags) )) .bind("test-worker") .fetch_one(&mut *conn) .await?; + // The variant fairness reserve workers resume through. + let fairness: Value = sqlx::query_scalar(&format!( + "EXPLAIN (FORMAT JSON) {}", + make_suspended_pull_query_fairness(&tags) + )) + .bind("test-worker") + .bind(vec!["overloaded-workspace".to_string()]) + .fetch_one(&mut *conn) + .await?; + assert_resume_test_in_index(&plain, &version)?; + assert_resume_test_in_index(&fairness, &version)?; + Ok(()) +} +fn assert_resume_test_in_index(explained: &Value, version: &str) -> anyhow::Result<()> { let mut all = vec![]; nodes(&explained[0]["Plan"], &mut all); - let pretty = serde_json::to_string_pretty(&explained)?; + let pretty = serde_json::to_string_pretty(explained)?; let scan = all .iter() .find(|n| n["Index Name"] == "queue_suspended_v2") diff --git a/backend/tests/trigger_hub_target.rs b/backend/tests/trigger_hub_target.rs index cb13c9ddb0..f42ff339b4 100644 --- a/backend/tests/trigger_hub_target.rs +++ b/backend/tests/trigger_hub_target.rs @@ -53,6 +53,7 @@ async fn hub_target_with_retry_runs_its_preprocessor(db: Pool) -> anyh is_admin: true, ..Default::default() }, + windmill_common::jobs::ChosenBy::Deployed, "test-workspace", &windmill_common::runnable_ref::RunnableRef::from_path( &format!("hub/{version}/test/pre"), diff --git a/backend/tests/trigger_listener_queries.rs b/backend/tests/trigger_listener_queries.rs index 88dcab82ac..c2392202a8 100644 --- a/backend/tests/trigger_listener_queries.rs +++ b/backend/tests/trigger_listener_queries.rs @@ -180,6 +180,7 @@ fn make_authed() -> windmill_api_auth::ApiAuthed { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/tests/volume_tests.rs b/backend/tests/volume_tests.rs index e93979e9c7..9584cb1ae0 100644 --- a/backend/tests/volume_tests.rs +++ b/backend/tests/volume_tests.rs @@ -468,7 +468,11 @@ fn test_volume_comment_prefix_selection() { fn test_volume_mount_struct() { use windmill_worker_volumes::VolumeMount; - let mount = VolumeMount { name: "test-vol".to_string(), target: "/mnt/data".to_string() }; + let mount = VolumeMount { + name: "test-vol".to_string(), + target: "/mnt/data".to_string(), + read_only: false, + }; assert_eq!(mount.name, "test-vol"); assert_eq!(mount.target, "/mnt/data"); } @@ -501,11 +505,13 @@ fn test_volume_nsjail_mount() { use std::path::Path; use windmill_worker_volumes::volume_nsjail_mount; - let result = volume_nsjail_mount(Path::new("/tmp/volumes/data"), "/mnt/data"); + let result = volume_nsjail_mount(Path::new("/tmp/volumes/data"), "/mnt/data", false); assert!(result.contains("src: \"/tmp/volumes/data\"")); assert!(result.contains("dst: \"/mnt/data\"")); assert!(result.contains("is_bind: true")); assert!(result.contains("rw: true")); + let read_only = volume_nsjail_mount(Path::new("/tmp/volumes/data"), "/mnt/data", true); + assert!(read_only.contains("rw: false")); } #[test] @@ -599,53 +605,10 @@ async fn run_volume_sql_worker_e2e( let server = ApiServer::start(db.clone()).await?; let port = server.addr.port(); - // 1. Set up filesystem-based object storage in a temp dir - let storage_dir = tempfile::tempdir()?; - let storage_root = storage_dir.path().to_string_lossy().to_string(); + let (_storage_dir, vol_dir) = setup_filesystem_volume(&db).await?; - let lfs_config = json!({ - "type": "FilesystemStorage", - "root_path": storage_root, - "public_resource": null, - "advanced_permissions": null, - "volume_storage": "primary" - }); - - sqlx::query!( - "UPDATE workspace_settings SET large_file_storage = $1 WHERE workspace_id = $2", - lfs_config, - "test-workspace" - ) - .execute(&db) - .await?; - - // 2. Pre-populate the volume with a file (workspace-namespaced path) - let vol_dir = storage_dir - .path() - .join("volumes") - .join("test-workspace") - .join("test-vol"); - std::fs::create_dir_all(&vol_dir)?; - std::fs::write(vol_dir.join("hello.txt"), b"hello from volume")?; - - // 3. Push the job and run with SQL-connected worker - let job = JobPayload::Code(RawCode { - hash: None, - content: code.to_string(), - path: None, - language, - lock: None, - 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, - }); - - let result = run_job_in_new_worker_until_complete(&db, false, job, port).await; + let result = + run_job_in_new_worker_until_complete(&db, false, raw_code_job(language, code), port).await; assert!(result.success, "job should succeed: {:?}", result.result); let json = result.json_result().expect("should have JSON result"); @@ -682,3 +645,139 @@ async fn run_volume_sql_worker_e2e( Ok(()) } + +/// A `volume:ro` mount takes no lease: it runs while another worker holds the volume, waits +/// only for that worker's write in progress (odd generation) to close, and writes nothing back. +#[cfg(all(feature = "parquet", feature = "private"))] +#[sqlx::test(fixtures("base"))] +async fn test_read_only_volume_ignores_lease_and_waits_for_write( + db: Pool, +) -> anyhow::Result<()> { + use windmill_common::min_version::{MIN_VERSION, MIN_VERSION_SUPPORTS_LEASE_FREE_VOLUMES}; + struct OnDrop(F); + impl Drop for OnDrop { + fn drop(&mut self) { + (self.0)() + } + } + // Put back for the rest of the binary, panics included + let before = MIN_VERSION.load_full(); + let _restore = OnDrop(move || MIN_VERSION.store(before.clone())); + MIN_VERSION.store(std::sync::Arc::new( + MIN_VERSION_SUPPORTS_LEASE_FREE_VOLUMES.version().clone(), + )); + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let (_storage_dir, vol_dir) = setup_filesystem_volume(&db).await?; + + sqlx::query!( + "INSERT INTO volume (workspace_id, name, size_bytes, created_by, lease_until, leased_by, generation) + VALUES ('test-workspace', 'test-vol', 0, 'test-user', now() + interval '1 hour', 'other-worker', 1)" + ) + .execute(&db) + .await?; + let db_c = db.clone(); + let hello = vol_dir.join("hello.txt"); + let writer = tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_secs(3)).await; + // A different length: the cache cannot tell same-size rewrites apart on a store + // whose etags are not content hashes. + std::fs::write(&hello, b"hello after the write").unwrap(); + sqlx::query!( + "UPDATE volume SET generation = 2 WHERE workspace_id = 'test-workspace' AND name = 'test-vol'" + ) + .execute(&db_c) + .await + }); + + let code = r#"// volume:ro test-vol data + +import { readFileSync, writeFileSync } from "fs"; + +export function main() { + const content = readFileSync("data/hello.txt", "utf-8"); + writeFileSync("data/output.txt", "discarded"); + return { read_content: content }; +}"#; + let result = + run_job_in_new_worker_until_complete(&db, false, raw_code_job(ScriptLang::Bun, code), port) + .await; + writer.await??; + + assert!(result.success, "job should succeed: {:?}", result.result); + assert_eq!( + result.json_result().unwrap()["read_content"], + json!("hello after the write"), + "the pull must wait for the write in progress" + ); + assert!( + !vol_dir.join("output.txt").exists(), + "a read-only mount must not write back" + ); + let row = sqlx::query!( + "SELECT leased_by, generation FROM volume WHERE workspace_id = 'test-workspace' AND name = 'test-vol'" + ) + .fetch_one(&db) + .await?; + assert_eq!(row.leased_by.as_deref(), Some("other-worker")); + assert_eq!(row.generation, 2); + Ok(()) +} + +#[cfg(feature = "parquet")] +fn raw_code_job(language: ScriptLang, code: &str) -> JobPayload { + JobPayload::Code(RawCode { + hash: None, + content: code.to_string(), + path: None, + language, + lock: None, + 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, + }) +} + +/// Filesystem object storage as the workspace's volume storage, holding `test-vol` with +/// `hello.txt`. Returns the storage dir (deleted on drop) and the volume's object dir. +#[cfg(feature = "parquet")] +async fn setup_filesystem_volume( + db: &Pool, +) -> anyhow::Result<(tempfile::TempDir, std::path::PathBuf)> { + // 1. Set up filesystem-based object storage in a temp dir + let storage_dir = tempfile::tempdir()?; + let storage_root = storage_dir.path().to_string_lossy().to_string(); + + let lfs_config = json!({ + "type": "FilesystemStorage", + "root_path": storage_root, + "public_resource": null, + "advanced_permissions": null, + "volume_storage": "primary" + }); + + sqlx::query!( + "UPDATE workspace_settings SET large_file_storage = $1 WHERE workspace_id = $2", + lfs_config, + "test-workspace" + ) + .execute(db) + .await?; + + // 2. Pre-populate the volume with a file (workspace-namespaced path) + let vol_dir = storage_dir + .path() + .join("volumes") + .join("test-workspace") + .join("test-vol"); + std::fs::create_dir_all(&vol_dir)?; + std::fs::write(vol_dir.join("hello.txt"), b"hello from volume")?; + + Ok((storage_dir, vol_dir)) +} diff --git a/backend/tests/wm_token_confinement.rs b/backend/tests/wm_token_confinement.rs index af5974f85a..6b995115c2 100644 --- a/backend/tests/wm_token_confinement.rs +++ b/backend/tests/wm_token_confinement.rs @@ -52,6 +52,7 @@ async fn wm_token(email: &str, is_admin: bool) -> String { scopes: None, token_prefix: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), }; create_jwt_token( authed, @@ -1129,6 +1130,7 @@ async fn test_privilege_gates_reject_a_job_token_directly( job_id, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/tests/worker.rs b/backend/tests/worker.rs index 6efdbd6414..5f5326ca76 100644 --- a/backend/tests/worker.rs +++ b/backend/tests/worker.rs @@ -164,6 +164,69 @@ async fn test_iteration_parallel(db: Pool) -> anyhow::Result<()> { Ok(()) } +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base"))] +async fn test_iteration_labels(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + + let label_loop = |id: &str, parallel: bool, label: &str| { + json!({ + "id": id, + "value": { + "type": "forloopflow", + "iterator": { "type": "javascript", "expr": "flow_input.items" }, + "skip_failures": false, + "parallel": parallel, + "iteration_label": { "type": "javascript", "expr": label }, + "modules": [ + { "id": format!("{id}_a"), "value": { "type": "identity" } }, + { "id": format!("{id}_b"), "value": { "type": "identity" } }, + ], + }, + }) + }; + let flow: FlowValue = serde_json::from_value(json!({ + "modules": [ + label_loop("seq", false, "flow_input.iter.value.name"), + label_loop("par", true, "`${flow_input.iter.index}:${flow_input.iter.value.name}`"), + label_loop("bad", false, "flow_input.iter.value.missing.name"), + ], + })) + .unwrap(); + + let job = RunJob::from(JobPayload::RawFlow { value: flow, path: None, restarted_from: None }) + .arg( + "items", + json!([{ "name": "acme" }, { "name": null }, { "name": "globex" }]), + ) + .run_until_complete(&db, false, server.addr.port()) + .await; + assert!(job.success, "{:?}", job.json_result()); + + let labels = |id: &str| get_module(&job, id).and_then(|m| m.flow_jobs_labels()); + assert_eq!( + labels("seq"), + Some(vec![ + Some("acme".to_string()), + None, + Some("globex".to_string()) + ]) + ); + assert_eq!( + labels("par"), + Some(vec![ + Some("0:acme".to_string()), + Some("1:null".to_string()), + Some("2:globex".to_string()) + ]) + ); + // A label that fails to evaluate leaves the iteration unlabelled and the loop running. + assert_eq!(labels("bad"), Some(vec![None, None, None])); + Ok(()) +} + #[cfg(feature = "deno_core")] #[sqlx::test(fixtures("base"))] async fn test_bun_flow(db: Pool) -> anyhow::Result<()> { @@ -221,6 +284,7 @@ async fn test_bun_flow(db: Pool) -> anyhow::Result<()> { skip_failures: false, parallel: false, squash: None, + iteration_label: None, parallelism: None, modules: vec![FlowModule { id: "c".to_string(), @@ -577,6 +641,7 @@ async fn test_bun_flow_same_worker(db: Pool) -> anyhow::Result<()> { skip_failures: false, parallel: false, squash: None, + iteration_label: None, parallelism: None, modules: vec![ FlowModule { @@ -1222,6 +1287,64 @@ class Script Ok(()) } +#[cfg(feature = "csharp")] +#[sqlx::test(fixtures("base"))] +async fn test_csharp_job_omitted_args_take_declared_defaults( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let job = || { + RunJob::from(JobPayload::Code(RawCode { + hash: None, + content: r#" +class Script +{ + const int Answer = 42; + // `params` is not in the parsed signature, so the wrapper never passes it. + public static string Main(string s = "World", int n = Answer, string @class = "c", params string[] rest) + { + return $"{s ?? ""} {n} {@class} {rest.Length}"; + } +} +"# + .to_owned(), + path: None, + lock: None, + language: ScriptLang::CSharp, + 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, + })) + }; + + let omitted = job() + .run_until_complete(&db, false, port) + .await + .json_result() + .unwrap(); + assert_eq!(omitted, json!("World 42 c 0")); + + let explicit = job() + .arg("s", json!(null)) + .arg("n", json!(1)) + .arg("@class", json!("k")) + .run_until_complete(&db, false, port) + .await + .json_result() + .unwrap(); + assert_eq!(explicit, json!(" 1 k 0")); + Ok(()) +} + #[sqlx::test(fixtures("base"))] async fn test_bash_job(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; @@ -4787,6 +4910,61 @@ async fn test_unrecoverable_failure_on_continue_on_error_runs_failure_module( Ok(()) } +/// A failure the flow goes past because of `continue_on_error` is recorded on the root flow's +/// status, including one inside a loop iteration's subflow. +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base"))] +async fn test_continue_on_error_recorded_on_root(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let failing = |id: &str| { + json!({"id": id, "continue_on_error": true, "value": { + "type": "rawscript", "language": "bun", "input_transforms": {}, + "content": "export function main() { throw new Error('boom'); }", + }}) + }; + let flow: FlowValue = serde_json::from_value(json!({ + "modules": [ + failing("a"), + {"id": "loop", "value": { + "type": "forloopflow", "parallel": true, "skip_failures": false, + "iterator": {"type": "static", "value": [1, 2]}, + "modules": [failing("b"), {"id": "c", "value": {"type": "identity"}}], + }}, + ], + })) + .unwrap(); + + let job = RunJob::from(JobPayload::RawFlow { value: flow, path: None, restarted_from: None }) + .run_until_complete(&db, false, port) + .await; + server.close().await.unwrap(); + + assert!(job.success, "{:?}", job.json_result()); + let mut recorded: Vec<(String, Uuid, Option)> = sqlx::query_as( + "SELECT e->>'id', (e->>'job')::uuid, j.parent_job + FROM v2_job_completed c, JSONB_ARRAY_ELEMENTS(c.flow_status->'continued_on_error') e + JOIN v2_job j ON j.id = (e->>'job')::uuid + WHERE c.id = $1", + ) + .bind(job.id) + .fetch_all(&db) + .await?; + recorded.sort(); + let ids: Vec<&str> = recorded.iter().map(|(id, ..)| id.as_str()).collect(); + assert_eq!(ids, vec!["a", "b", "b"]); + assert_eq!(recorded[0].2, Some(job.id)); + assert_ne!(recorded[1].1, recorded[2].1); + assert_ne!( + recorded[1].2, + Some(job.id), + "b runs in an iteration's subflow" + ); + Ok(()) +} + #[cfg(feature = "deno_core")] #[sqlx::test(fixtures("base"))] async fn test_run_wait_result_early_return_with_failure_module( diff --git a/backend/tests/workspace_export.rs b/backend/tests/workspace_export.rs index 792d41b487..292d1aaaac 100644 --- a/backend/tests/workspace_export.rs +++ b/backend/tests/workspace_export.rs @@ -373,9 +373,11 @@ async fn test_tarball_export_settings_are_admin_only(db: Pool) -> anyh let (status, body) = export("SECRET_TOKEN").await?; assert_eq!(status, 200, "admin denied settings: {body}"); + assert!(body.contains("AI_CONFIG_SECRET"), "admin got no settings"); + // The webhook URL carries the receiver's token, so it leaves encrypted. assert!( - body.contains("WEBHOOK_SECRET") && body.contains("AI_CONFIG_SECRET"), - "admin got no settings" + body.contains(r#""webhook": "$encrypted:"#) && !body.contains("WEBHOOK_SECRET"), + "webhook not exported encrypted: {body}" ); // Git sync pushes the workspace to the repo by exporting it under @@ -397,7 +399,7 @@ async fn test_tarball_export_settings_are_admin_only(db: Pool) -> anyh let (status, body) = export(&sync_token).await?; assert_eq!(status, 200, "git-sync identity denied settings: {body}"); assert!( - body.contains("WEBHOOK_SECRET"), + body.contains("AI_CONFIG_SECRET"), "git-sync identity got no settings" ); diff --git a/backend/windmill-ai/src/ai_bedrock.rs b/backend/windmill-ai/src/ai_bedrock.rs index f55fcca415..ce34dcc97c 100644 --- a/backend/windmill-ai/src/ai_bedrock.rs +++ b/backend/windmill-ai/src/ai_bedrock.rs @@ -612,7 +612,7 @@ pub fn openai_messages_to_bedrock( })?; bedrock_messages.push(tool_result_message); } - bedrock_messages.push(convert_message(msg)?); + push_alternating(&mut bedrock_messages, convert_message(msg)?)?; } "tool" => { // Accumulate tool results - they will be flushed as a single message @@ -646,6 +646,27 @@ pub fn openai_messages_to_bedrock( Ok((bedrock_messages, system_prompts)) } +/// Push a message, folding it into the previous one when both are the user's: an agent's +/// background-tool results arrive as user messages, right after tool results or each other. +fn push_alternating(messages: &mut Vec, message: Message) -> Result<(), Error> { + match messages.last_mut() { + Some(last) + if *last.role() == ConversationRole::User + && *message.role() == ConversationRole::User => + { + let mut content = last.content().to_vec(); + content.extend(message.content().iter().cloned()); + *last = Message::builder() + .role(ConversationRole::User) + .set_content(Some(content)) + .build() + .map_err(|e| Error::internal_err(format!("Failed to merge user messages: {e}")))?; + } + _ => messages.push(message), + } + Ok(()) +} + /// Helper to extract text from OpenAIContent (ignoring images) /// /// This is public so it can be reused by the worker module. @@ -1511,6 +1532,37 @@ mod tests { )); } + #[test] + fn openai_messages_to_bedrock_keeps_roles_alternating() { + let tool_result = OpenAIMessage { + role: "tool".to_string(), + content: Some(OpenAIContent::Text("started".to_string())), + tool_call_id: Some("call_1".to_string()), + ..Default::default() + }; + let messages = vec![ + text_message("user", "Export the report"), + text_message("assistant", "Exporting"), + tool_result, + text_message("user", "Background tool finished"), + text_message("user", "Another background tool finished"), + ]; + + let (bedrock_messages, _) = + openai_messages_to_bedrock(&messages, false).expect("bedrock conversion succeeds"); + + let roles: Vec<_> = bedrock_messages.iter().map(|m| m.role().clone()).collect(); + assert_eq!( + roles, + vec![ + ConversationRole::User, + ConversationRole::Assistant, + ConversationRole::User + ] + ); + assert_eq!(bedrock_messages[2].content().len(), 3); + } + #[test] fn build_tool_config_adds_cache_point_when_enabled() { let tools = vec![test_tool()]; diff --git a/backend/windmill-ai/src/ai_providers.rs b/backend/windmill-ai/src/ai_providers.rs index 489a965ef1..5947da0340 100644 --- a/backend/windmill-ai/src/ai_providers.rs +++ b/backend/windmill-ai/src/ai_providers.rs @@ -172,10 +172,10 @@ impl AIProvider { matches!(self, AIProvider::TypeSafe | AIProvider::Cloudflare) } - /// A provider an AI decision runs on: the decision providers, and OpenAI, whose Decisions - /// API sits next to its chat routes on the same resource. + /// A provider an AI decision runs on: the decision providers, and OpenAI and Google AI, whose + /// Decisions APIs sit next to their chat routes on the same resource. pub fn runs_decisions(&self) -> bool { - self.is_decision_provider() || matches!(self, AIProvider::OpenAI) + self.is_decision_provider() || matches!(self, AIProvider::OpenAI | AIProvider::GoogleAI) } /// Get the base URL for the AI provider diff --git a/backend/windmill-ai/src/credentials.rs b/backend/windmill-ai/src/credentials.rs index f5489c5c30..3239e9e5ac 100644 --- a/backend/windmill-ai/src/credentials.rs +++ b/backend/windmill-ai/src/credentials.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; use crate::ai_providers::{AIPlatform, AIProvider}; +use crate::vertex_workload_identity::VertexWorkloadIdentity; /// Resolved provider credentials shared by API proxy and worker execution. /// @@ -36,6 +37,11 @@ pub struct ProviderCredentials { /// resource. The API proxy exchanges an OIDC token minted for the requesting /// user for a short-lived access token, which then goes out as `access_token`. pub anthropic_federation: Option, + /// Google Cloud Workload Identity Federation settings, from a `vertex_ai_federated` + /// resource. The OIDC token is exchanged for a Google access token, sent as + /// the Vertex bearer token: by the API proxy for the requesting user, by the + /// worker for the job. + pub vertex_workload_identity: Option, pub platform: AIPlatform, pub custom_headers: HashMap, } diff --git a/backend/windmill-ai/src/decision.rs b/backend/windmill-ai/src/decision.rs index b3a35dab2a..f35b3e2f0f 100644 --- a/backend/windmill-ai/src/decision.rs +++ b/backend/windmill-ai/src/decision.rs @@ -1,7 +1,7 @@ //! AI decision steps: one call to a decision endpoint, which answers typed questions (`choice`, //! `score`, `noul`) about a state with calibrated probabilities instead of text. The questions and //! answers are System One's (TypeSafe's Jev, Cloudflare's Jev-compatible Clef on Workers AI); -//! OpenAI's Decisions API is asked and read through a translation to that shape. +//! OpenAI's and Gemini's Decisions APIs are asked and read through a translation to that shape. use std::time::Duration; @@ -10,7 +10,7 @@ use serde_json::{value::RawValue, Map, Value}; use windmill_common::error::{Error, Result}; use crate::{ - ai_providers::AIProvider, + ai_providers::{AIPlatform, AIProvider}, credentials::ProviderCredentials, proxy::{common_outbound_headers, retain_effective_credentials}, types::{ProviderWithResource, TokenUsage}, @@ -33,6 +33,8 @@ pub const TYPESAFE_DEFAULT_MODEL: &str = "jev-latest"; pub const CLOUDFLARE_DEFAULT_MODEL: &str = "clef"; /// The model OpenAI's Decisions API serves, run when the step names none. pub const OPENAI_DEFAULT_MODEL: &str = "gpt-6-luna"; +/// The model Gemini's Decisions API serves, run when the step names none. +pub const GOOGLE_DEFAULT_MODEL: &str = "gemini-decision-1"; #[derive(Serialize)] struct SystemOneRequest<'a> { @@ -111,7 +113,7 @@ pub fn decision_inputs<'a>( Ok((state, questions)) } -/// Posts a decision request with the resource's bearer key and returns the response body. +/// Posts a decision request with the resource's key and returns the response body. async fn post_decision( credentials: &ProviderCredentials, endpoint: &str, @@ -119,16 +121,13 @@ async fn post_decision( payload: &T, timeout: Duration, ) -> Result { - let auth_headers = retain_effective_credentials( - credentials, - vec![( - "Authorization", - format!( - "Bearer {}", - credentials.api_key.as_deref().unwrap_or_default() - ), - )], - ); + let api_key = credentials.api_key.as_deref().unwrap_or_default(); + let auth_header = if credentials.provider == AIProvider::GoogleAI { + ("x-goog-api-key", api_key.to_string()) + } else { + ("Authorization", format!("Bearer {api_key}")) + }; + let auth_headers = retain_effective_credentials(credentials, vec![auth_header]); // The endpoint derives from the resource's base URL, so the connect is pinned to the // address the SSRF check validated. @@ -172,13 +171,176 @@ pub async fn run_decision( questions: &Map, timeout: Duration, ) -> Result { - if credentials.provider == AIProvider::OpenAI { - run_openai_decisions(credentials, model, state, questions, timeout).await - } else { - run_systemone(credentials, model, state, questions, timeout).await + match credentials.provider { + AIProvider::OpenAI => { + run_openai_decisions(credentials, model, state, questions, timeout).await + } + AIProvider::GoogleAI => { + run_gemini_decisions(credentials, model, state, questions, timeout).await + } + _ => run_systemone(credentials, model, state, questions, timeout).await, } } +#[derive(Serialize)] +struct GeminiDecisionsRequest<'a> { + model: &'a str, + input: Value, + questions: Map, +} + +#[derive(Deserialize)] +struct GeminiDecisionsResponse { + #[serde(default)] + model: Option, + #[serde(default)] + answers: Option>, + #[serde(default)] + usage: Option, + #[serde(default)] + prompt_feedback: Option>, +} + +#[derive(Deserialize)] +struct GeminiUsage { + total_input_tokens: Option, + total_output_tokens: Option, +} + +/// The content types a Gemini Decisions input block has. +const GEMINI_BLOCK_TYPES: [&str; 5] = ["text", "image", "audio", "video", "document"]; + +/// The state as a Gemini Decisions `input`: a text, or a content block or list of them (the way to +/// pass an image or a document) as it is, and any other object or array as its JSON text. +fn gemini_input(state: &Value) -> Value { + let is_block = |block: &Value| match block.get("type").and_then(Value::as_str) { + Some("text") => block.get("text").is_some_and(Value::is_string), + Some(kind) if GEMINI_BLOCK_TYPES.contains(&kind) => { + block.get("mime_type").is_some_and(Value::is_string) + && (block.get("data").is_some_and(Value::is_string) + || block.get("uri").is_some_and(Value::is_string)) + } + _ => false, + }; + match state { + Value::String(_) => state.clone(), + Value::Object(_) if is_block(state) => state.clone(), + Value::Array(blocks) if !blocks.is_empty() && blocks.iter().all(is_block) => state.clone(), + _ => Value::String(state.to_string()), + } +} + +/// The questions as Gemini takes them. They are keyed and typed as System One's are; a `noul`'s +/// meanings go as `true_description`/`false_description`, and a structured description, option +/// or level as its JSON text, since Gemini reads only texts there. +fn gemini_questions(questions: &Map) -> Map { + let text = |v: &Value| match v { + Value::String(s) => Value::String(s.clone()), + v => Value::String(v.to_string()), + }; + questions + .iter() + .map(|(name, question)| { + let mut asked = question.as_object().cloned().unwrap_or_default(); + let kind = asked.get("type").and_then(Value::as_str).map(str::to_owned); + let criteria = match (kind.as_deref(), asked.remove("criteria")) { + (Some("noul"), Some(Value::Object(meanings))) => Some(Value::Object( + [("true", "true_description"), ("false", "false_description")] + .into_iter() + .filter_map(|(key, field)| match meanings.get(key) { + None | Some(Value::Null) => None, + Some(d) => Some((field.to_string(), text(d))), + }) + .collect(), + )), + (Some("choice"), Some(Value::Object(options))) => Some(Value::Object( + options + .into_iter() + .map(|(option, d)| { + let d = match d { + Value::Null => Value::Null, + d => text(&d), + }; + (option, d) + }) + .collect(), + )), + (Some("score"), Some(Value::Array(levels))) => { + Some(Value::Array(levels.iter().map(text).collect())) + } + (_, criteria) => criteria, + }; + if let Some(criteria) = criteria { + asked.insert("criteria".to_string(), criteria); + } + if let Some(instructions) = asked.get_mut("instructions") { + if !instructions.is_string() { + *instructions = text(instructions); + } + } + (name.clone(), Value::Object(asked)) + }) + .collect() +} + +async fn run_gemini_decisions( + credentials: &ProviderCredentials, + model: &str, + state: &Value, + questions: &Map, + timeout: Duration, +) -> Result { + if credentials.platform == AIPlatform::GoogleVertexAi { + return Err(Error::BadRequest( + "Gemini's Decisions API is served by the Gemini API, not Vertex AI: use a Google AI \ + resource on the standard platform" + .to_string(), + )); + } + let model = match model.trim() { + "" => GOOGLE_DEFAULT_MODEL, + model => model.strip_prefix("models/").unwrap_or(model), + }; + let endpoint = format!("{}/decisions", credentials.base_url.trim_end_matches('/')); + let body = post_decision( + credentials, + &endpoint, + "Gemini", + &GeminiDecisionsRequest { + model, + input: gemini_input(state), + questions: gemini_questions(questions), + }, + timeout, + ) + .await?; + let parsed = serde_json::from_str::(&body) + .map_err(|e| Error::ExecutionErr(format!("Unexpected Gemini response ({e}): {body}")))?; + // A blocked prompt comes back with no answers; left as an empty output, a branch on it would + // quietly take its default arm. + if let Some(feedback) = parsed + .prompt_feedback + .filter(|f| f.get("block_reason").is_some_and(|r| !r.is_null())) + { + return Err(Error::ExecutionErr(format!( + "Gemini blocked the decision: {}", + Value::Object(feedback) + ))); + } + let output = parsed.answers.ok_or_else(|| { + Error::ExecutionErr(format!("Unexpected Gemini response (no answers): {body}")) + })?; + + Ok(DecisionResult { + output, + model: parsed.model, + usage: parsed + .usage + .map(|u| TokenUsage::from_input_output(u.total_input_tokens, u.total_output_tokens)) + .filter(|u| !u.is_empty()), + }) +} + #[derive(Serialize)] struct OpenAIDecisionsRequest<'a> { model: &'a str, @@ -521,6 +683,40 @@ mod tests { assert!(openai_answers(refused).is_err()); } + /// A `noul`'s meanings go out under Gemini's field names and structured texts as JSON text; + /// content blocks pass through as the input, anything else structured goes as its JSON text. + #[test] + fn gemini_questions_and_input_translate() { + let questions = json!({ + "intent": {"type": "choice", "instructions": "Why?", "criteria": {"refund": {"when": "paid"}, "bug": null}}, + "urgency": {"type": "score", "instructions": "How urgent?", "criteria": ["Can wait", 2]}, + "angry": {"type": "noul", "instructions": {"t": 1}, "criteria": {"true": "Insults", "false": null}} + }); + assert_eq!( + Value::Object(gemini_questions(questions.as_object().unwrap())), + json!({ + "intent": {"type": "choice", "instructions": "Why?", "criteria": {"refund": "{\"when\":\"paid\"}", "bug": null}}, + "urgency": {"type": "score", "instructions": "How urgent?", "criteria": ["Can wait", "2"]}, + "angry": {"type": "noul", "instructions": "{\"t\":1}", "criteria": {"true_description": "Insults"}} + }) + ); + + let image = json!({"type": "image", "mime_type": "image/png", "data": "iVBOR"}); + let blocks = json!([{"type": "text", "text": "hi"}, image]); + assert_eq!(gemini_input(&json!("hi")), json!("hi")); + assert_eq!(gemini_input(&image), image); + assert_eq!(gemini_input(&blocks), blocks); + for other in [ + json!({"m": "hi"}), + json!([]), + json!([{"type": "text", "text": "hi"}, "plain"]), + json!([{"type": "image", "data": "iVBOR"}]), + json!([{"type": "input_text", "text": "hi"}]), + ] { + assert_eq!(gemini_input(&other), json!(other.to_string()), "{other}"); + } + } + /// Refused are the values a flow produces when it forgot the input (no key, `null`, a blank /// string from an empty expression) and the scalars TypeSafe rejects. A text, an object or an /// array is a state, whatever it holds. diff --git a/backend/windmill-ai/src/lib.rs b/backend/windmill-ai/src/lib.rs index 39ef1eee4d..b137d01f4d 100644 --- a/backend/windmill-ai/src/lib.rs +++ b/backend/windmill-ai/src/lib.rs @@ -16,4 +16,5 @@ pub mod retry; pub mod sse; pub mod types; pub mod utils; +pub mod vertex_workload_identity; pub mod web_search; diff --git a/backend/windmill-ai/src/model_context.rs b/backend/windmill-ai/src/model_context.rs index 4b7b8fd68d..b10345073d 100644 --- a/backend/windmill-ai/src/model_context.rs +++ b/backend/windmill-ai/src/model_context.rs @@ -77,16 +77,6 @@ fn bare_model_id(model: &str) -> String { base.replace('.', "-") } -/// Whether this is one of OpenAI's reasoning models (gpt-5 and later, the o-series), -/// which think by default. Mirrors `requiresMaxCompletionTokens` in the frontend's -/// `modelConfig.ts`: the o-series match wants a digit after the `o` so that ids such -/// as `open-mistral-*` stay out. -pub fn is_openai_reasoning_model(model: &str) -> bool { - let id = bare_model_id(model); - id.starts_with("gpt-5") - || (id.starts_with('o') && id[1..].starts_with(|c: char| c.is_ascii_digit())) -} - /// The window this model is known to hold, `None` for one not in the table. fn known_model_context_window(model: &str) -> Option { let id = bare_model_id(model); diff --git a/backend/windmill-ai/src/providers/anthropic.rs b/backend/windmill-ai/src/providers/anthropic.rs index 2a3417bc62..64e02664f4 100644 --- a/backend/windmill-ai/src/providers/anthropic.rs +++ b/backend/windmill-ai/src/providers/anthropic.rs @@ -1,4 +1,7 @@ -use super::{anthropic_model_rejects_sampling_params, REASONING_OFF_SENTINEL}; +use super::{ + anthropic_model_rejects_sampling_params, force_claude_structured_output_tool, + REASONING_OFF_SENTINEL, +}; use crate::{ ai_google::parse_data_url, ai_providers::{AIPlatform, AIProvider, DISABLE_ANTHROPIC_PROMPT_CACHING}, @@ -653,8 +656,10 @@ impl AnthropicQueryBuilder { let should_use_structured_output = should_use_structured_output_tool(&self.provider_kind, args.model); - // Force tool usage when structured output is needed - let tool_choice = if should_use_structured_output && has_output_properties { + let tool_choice = if should_use_structured_output + && has_output_properties + && force_claude_structured_output_tool(args.model, args.reasoning_effort) + { Some(AnthropicToolChoice::any()) } else { None @@ -1024,6 +1029,7 @@ mod tests { aws_session_token: None, oidc_role_arn: None, anthropic_federation: None, + vertex_workload_identity: None, platform, custom_headers: HashMap::new(), } diff --git a/backend/windmill-ai/src/providers/bedrock.rs b/backend/windmill-ai/src/providers/bedrock.rs index 5aa142a127..1c400d9cdf 100644 --- a/backend/windmill-ai/src/providers/bedrock.rs +++ b/backend/windmill-ai/src/providers/bedrock.rs @@ -6,7 +6,10 @@ //! - Stream event parsing //! - Helper utilities -use super::{anthropic_model_rejects_sampling_params, REASONING_OFF_SENTINEL}; +use super::{ + anthropic_model_rejects_sampling_params, force_claude_structured_output_tool, + REASONING_OFF_SENTINEL, +}; use crate::{ ai_bedrock::{ bedrock_model_supports_prompt_caching, bedrock_stream_error, @@ -1004,10 +1007,11 @@ impl BedrockQueryBuilder { // Build inference configuration using shared helper let inference_config = create_inference_config(temperature, max_tokens.map(|t| t as i32)); - // Build tool configuration with optional ToolChoice let tool_config = build_tool_config( tools, - structured_output_tool_name.is_some(), + structured_output_tool_name.is_some() + && (!model.to_lowercase().contains("claude") + || force_claude_structured_output_tool(model, reasoning_effort)), enable_prompt_caching, )?; diff --git a/backend/windmill-ai/src/providers/google_ai.rs b/backend/windmill-ai/src/providers/google_ai.rs index 06a404e5a4..cd67e0ebfe 100644 --- a/backend/windmill-ai/src/providers/google_ai.rs +++ b/backend/windmill-ai/src/providers/google_ai.rs @@ -806,6 +806,7 @@ mod tests { aws_session_token: None, oidc_role_arn: None, anthropic_federation: None, + vertex_workload_identity: None, platform, custom_headers: HashMap::new(), } diff --git a/backend/windmill-ai/src/providers/mod.rs b/backend/windmill-ai/src/providers/mod.rs index ffddd33d3a..cf0f9b8f8c 100644 --- a/backend/windmill-ai/src/providers/mod.rs +++ b/backend/windmill-ai/src/providers/mod.rs @@ -30,6 +30,36 @@ pub fn effective_reasoning_effort<'a>(model: &str, effort: Option<&'a str>) -> O } } +/// Providers ignore the limit field they don't read, so a wrong pick silently lifts the +/// limit: DeepSeek reads only `max_tokens`, OpenAI's reasoning models refuse it, and +/// Azure deployment and Custom AI model names don't reveal the model behind them. +pub fn reads_max_completion_tokens(provider: &AIProvider) -> bool { + matches!( + provider, + AIProvider::OpenAI + | AIProvider::AzureOpenAI + | AIProvider::AzureFoundry + | AIProvider::CustomAI + | AIProvider::Groq + | AIProvider::OpenRouter + ) +} + +/// Whether this is one of OpenAI's reasoning models (gpt-5 and later, the o-series), +/// which think by default and refuse `max_tokens`. Mirrors `requiresMaxCompletionTokens` +/// in the frontend's `modelConfig.ts`. +pub fn is_openai_reasoning_model(model: &str) -> bool { + let model = model.to_lowercase(); + let model = model.strip_prefix('~').unwrap_or(&model); + gpt_version(model).is_some_and(|(major, _)| major >= 5) || is_o_series(model) +} + +/// o1, o3, o4-mini… The digit keeps out ids such as `open-mistral-*` and `optimus-*`. +fn is_o_series(model: &str) -> bool { + let base = base_id(model); + base.starts_with('o') && base[1..].starts_with(|c: char| c.is_ascii_digit()) +} + /// 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) @@ -98,14 +128,7 @@ const REASONING_RULES: &[ReasoningRule] = &[ can_disable: false, completions_tools_need_off: false, }, - ReasoningRule { - matches: |m| { - let base = base_id(m); - base.starts_with('o') && base[1..].starts_with(|c: char| c.is_ascii_digit()) - }, - can_disable: false, - completions_tools_need_off: false, - }, + ReasoningRule { matches: is_o_series, can_disable: false, completions_tools_need_off: false }, ]; fn reasoning_rule(model: &str) -> Option<&'static ReasoningRule> { @@ -173,6 +196,27 @@ pub(crate) fn anthropic_model_rejects_sampling_params(model: &str) -> bool { || model.contains("claude-mythos") } +/// Whether to force the structured output tool on a Claude model. Unforced, Claude 3 and 4 +/// often write prose before calling it, and a small `max_tokens` then cuts the call off. +/// Every Claude model rejects a forced tool while thinking, and Sonnet/Opus 5.5 and Fable 5.x +/// reject it outright, so newer models are only told to call it. +pub(crate) fn force_claude_structured_output_tool( + model: &str, + reasoning_effort: Option<&str>, +) -> bool { + let thinking = reasoning_effort.is_some_and(|effort| effort != REASONING_OFF_SENTINEL); + let model = model.to_lowercase().replace('.', "-"); + !thinking + && [ + "claude-3", + "claude-opus-4", + "claude-sonnet-4", + "claude-haiku-4", + ] + .iter() + .any(|generation| model.contains(generation)) +} + use windmill_common::cache::Cache; use crate::{ @@ -268,6 +312,36 @@ pub fn remember_chat_completions_only(base_url: &str, model: &str) { mod reasoning_rule_tests { use super::*; + /// Probed against the Messages API: forcing 400s on Sonnet/Opus 5.5 and Fable 5.x. + #[test] + fn forces_the_structured_output_tool_only_on_claude_3_and_4_without_thinking() { + for model in [ + "claude-haiku-4-5-20251001", + "claude-3-7-sonnet-latest", + "anthropic/claude-sonnet-4.5", + "us.anthropic.claude-opus-4-1-20250805-v1:0", + "claude-sonnet-4-5@20250929", + ] { + assert!(force_claude_structured_output_tool(model, None), "{model}"); + assert!( + force_claude_structured_output_tool(model, Some(REASONING_OFF_SENTINEL)), + "{model}" + ); + assert!( + !force_claude_structured_output_tool(model, Some("high")), + "{model}" + ); + } + for model in [ + "claude-sonnet-5-5", + "claude-opus-5-5", + "claude-fable-5-2", + "anthropic/claude-sonnet-5.5", + ] { + assert!(!force_claude_structured_output_tool(model, None), "{model}"); + } + } + /// The frontend registry's test reads the same file. These rules see the model id /// alone, so it holds only rows whose answer doesn't depend on the provider. #[test] @@ -302,6 +376,41 @@ mod reasoning_rule_tests { assert!(completions_tools_need_reasoning_off("openai/gpt-6-sol")); assert_eq!(effective_reasoning_effort("openai/o3", Some("none")), None); } + + /// The frontend's `requiresMaxCompletionTokens` cases in `lib.test.ts`, plus the id + /// forms its `parseModelId` handles and the version edges: `~`, `:tag`, gpt-6, gpt-50. + #[test] + fn is_openai_reasoning_model_matches_the_frontend() { + for model in [ + "gpt-5", + "gpt-5.5", + "gpt-5-mini", + "o1", + "o3", + "o4-mini", + "openai/gpt-5", + "openai/o3", + "~openai/gpt-5", + "gpt-5:free", + "GPT-6-astra", + ] { + assert!(is_openai_reasoning_model(model), "{model}"); + } + for model in [ + "gpt-4o", + "gpt-4o-mini", + "openai/gpt-4o", + "open-mistral-7b", + "open-mixtral-8x7b", + "open-mistral-nemo-2407", + "optimus-alpha", + "openchat/openchat-7b", + "gpt-50", + "gpt-10", + ] { + assert!(!is_openai_reasoning_model(model), "{model}"); + } + } } #[cfg(test)] @@ -371,6 +480,7 @@ mod parity_tests { aws_session_token: None, oidc_role_arn: None, anthropic_federation: None, + vertex_workload_identity: None, platform: kase.platform.clone(), custom_headers: HashMap::new(), } diff --git a/backend/windmill-ai/src/providers/other.rs b/backend/windmill-ai/src/providers/other.rs index fea8edbdac..df9cd60487 100644 --- a/backend/windmill-ai/src/providers/other.rs +++ b/backend/windmill-ai/src/providers/other.rs @@ -1,4 +1,7 @@ -use super::{completions_tools_need_reasoning_off, REASONING_OFF_SENTINEL}; +use super::{ + completions_tools_need_reasoning_off, force_claude_structured_output_tool, + reads_max_completion_tokens, REASONING_OFF_SENTINEL, +}; use crate::{ ai_providers::AIProvider, image_handler::prepare_messages_for_api, @@ -41,6 +44,9 @@ pub struct OpenAICompletionRequest<'a> { /// token (`reasoning_effort: "none"` is rejected by their API). #[serde(skip_serializing_if = "Option::is_none")] pub thinking: Option, + /// At most one of the two limit fields is set: `reads_max_completion_tokens` picks which. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_tokens: Option, #[serde(skip_serializing_if = "Option::is_none")] pub max_completion_tokens: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -135,8 +141,10 @@ impl OtherQueryBuilder { None }; - // Force usage of structured output tool for Claude models when structured output is provided - let tool_choice = if should_use_structured_output_tool && has_output_properties { + let tool_choice = if should_use_structured_output_tool + && has_output_properties + && force_claude_structured_output_tool(args.model, args.reasoning_effort) + { Some(ToolChoice::Required) } else { None @@ -154,6 +162,13 @@ impl OtherQueryBuilder { reasoning_effort }; + let (max_tokens, max_completion_tokens) = + if reads_max_completion_tokens(&self.provider_kind) { + (None, args.max_tokens) + } else { + (args.max_tokens, None) + }; + // Build request with stream_options for usage tracking let request_with_usage = OpenAICompletionRequest { model: args.model, @@ -162,7 +177,8 @@ impl OtherQueryBuilder { temperature, reasoning_effort, thinking: thinking.clone(), - max_completion_tokens: args.max_tokens, + max_tokens, + max_completion_tokens, response_format: response_format.clone(), tool_choice: tool_choice.clone(), stream: true, @@ -177,7 +193,8 @@ impl OtherQueryBuilder { temperature, reasoning_effort, thinking, - max_completion_tokens: args.max_tokens, + max_tokens, + max_completion_tokens, response_format, tool_choice, stream: true, @@ -366,4 +383,66 @@ mod tests { assert!(thinking.is_none()); assert_eq!(temperature, Some(0.3)); } + + #[tokio::test] + async fn writes_the_limit_in_the_one_field_the_provider_reads() { + let client = AuthedClient::new( + "http://localhost:8000".to_string(), + "ws".to_string(), + "token".to_string(), + None, + ); + let messages = vec![OpenAIMessage { + role: "user".to_string(), + content: Some(OpenAIContent::Text("hi".to_string())), + ..Default::default() + }]; + // The field each provider must get the limit in; `None` is a request with no limit. + #[rustfmt::skip] + let cases: &[(AIProvider, &str, Option<&str>)] = &[ + (AIProvider::OpenAI, "gpt-4o", Some("max_completion_tokens")), + (AIProvider::AzureOpenAI, "my-deployment", Some("max_completion_tokens")), + (AIProvider::Groq, "llama-3.3-70b", Some("max_completion_tokens")), + (AIProvider::OpenRouter, "meta-llama/llama-3", Some("max_completion_tokens")), + (AIProvider::AzureFoundry, "Llama-3.3-70B-Instruct", Some("max_completion_tokens")), + (AIProvider::CustomAI, "production", Some("max_completion_tokens")), + (AIProvider::DeepSeek, "deepseek-flash", Some("max_tokens")), + (AIProvider::Mistral, "mistral-medium-latest", Some("max_tokens")), + (AIProvider::TogetherAI, "meta-llama/Llama-3-8b", Some("max_tokens")), + (AIProvider::DeepSeek, "deepseek-flash", None), + ]; + for (provider, model, field) in cases { + let args = BuildRequestArgs { + messages: &messages, + tools: None, + model, + temperature: None, + reasoning_effort: None, + max_tokens: field.map(|_| 40), + output_schema: None, + output_type: &OutputType::Text, + system_prompt: None, + user_message: "hi", + attachments: None, + has_websearch: false, + prompt_cache_key: None, + reasoning_summary: false, + }; + let built = OtherQueryBuilder::new(provider.clone()) + .build_text_requests(&args, &client, "ws") + .await + .unwrap(); + for body in [built.with_usage, built.without_usage] { + let body: serde_json::Value = serde_json::from_str(&body).unwrap(); + for name in ["max_tokens", "max_completion_tokens"] { + let expected = (Some(name) == *field).then(|| serde_json::json!(40)); + assert_eq!( + body.get(name).cloned(), + expected, + "{provider:?} {model} {name}" + ); + } + } + } + } } diff --git a/backend/windmill-ai/src/proxy.rs b/backend/windmill-ai/src/proxy.rs index 66285437e4..9503066ce8 100644 --- a/backend/windmill-ai/src/proxy.rs +++ b/backend/windmill-ai/src/proxy.rs @@ -286,6 +286,7 @@ mod tests { aws_session_token: None, oidc_role_arn: None, anthropic_federation: None, + vertex_workload_identity: None, platform: AIPlatform::Standard, custom_headers: HashMap::new(), } diff --git a/backend/windmill-ai/src/types.rs b/backend/windmill-ai/src/types.rs index 267e16c6eb..4454ac86ff 100644 --- a/backend/windmill-ai/src/types.rs +++ b/backend/windmill-ai/src/types.rs @@ -16,6 +16,7 @@ pub struct McpToolSource { pub resource_path: String, } +use crate::vertex_workload_identity::VertexWorkloadIdentity; use crate::{ ai_google::sanitize_schema_for_google, ai_providers::{empty_string_as_none, AIProvider}, @@ -65,6 +66,9 @@ pub struct Tool { /// Set on the built-in question tool, which the worker answers by parking the agent until /// someone answers or this many seconds pass. pub question_timeout_secs: Option, + /// A flow module tool whose call is answered once its job is queued (`Some(0)`) or, unfinished, + /// this many seconds after; see `AgentTool::background`. + pub background_after_secs: Option, } #[derive(Deserialize, Serialize, Debug, Clone, PartialEq)] @@ -285,6 +289,14 @@ pub struct ProviderResource { pub service_account_id: Option, #[serde(default, deserialize_with = "empty_string_as_none")] pub workspace_id: Option, + /// Set only by `vertex_ai_federated` resources, which authenticate to Vertex AI + /// through Google Cloud Workload Identity Federation. + #[serde(default, deserialize_with = "empty_string_as_none")] + pub workload_identity_provider: Option, + #[serde(default, deserialize_with = "empty_string_as_none")] + pub service_account_email: Option, + #[serde(default, deserialize_with = "empty_string_as_none")] + pub workload_identity_audience: Option, /// The API token of a `cloudflare` resource, which names it `token` rather than `api_key`. #[serde(default, deserialize_with = "empty_string_as_none")] pub token: Option, @@ -339,6 +351,17 @@ impl ProviderWithResource { /// current job/workspace; this helper does not perform access checks. pub async fn to_provider_credentials(&self, db: &DB) -> Result { let anthropic_federation = self.anthropic_federation()?; + let vertex_workload_identity = VertexWorkloadIdentity::from_resource( + &self.kind, + self.resource.workload_identity_provider.as_deref(), + self.resource.service_account_email.as_deref(), + self.resource.workload_identity_audience.as_deref(), + )?; + let platform = if vertex_workload_identity.is_some() { + AIPlatform::GoogleVertexAi + } else { + self.resource.platform.clone() + }; let base_url = if self.kind == AIProvider::AWSBedrock { String::new() } else if anthropic_federation.is_some() { @@ -369,7 +392,8 @@ impl ProviderWithResource { aws_session_token: self.resource.aws_session_token.clone(), oidc_role_arn: self.resource.oidc_role_arn.clone(), anthropic_federation, - platform: self.resource.platform.clone(), + vertex_workload_identity, + platform, custom_headers: self.resource.headers.clone(), }) } @@ -553,6 +577,9 @@ pub enum StreamingEvent { ToolExecution { call_id: String, function_name: String }, /// Tool execution result ToolResult { call_id: String, function_name: String, result: String, success: bool }, + /// The agent has answered and waits, without a worker, on tools still running in the + /// background: nothing more streams until one of them finishes and wakes it. + BackgroundWait, } #[derive(Serialize, Deserialize, Clone, Debug)] diff --git a/backend/windmill-ai/src/vertex_workload_identity.rs b/backend/windmill-ai/src/vertex_workload_identity.rs new file mode 100644 index 0000000000..9dabebadb5 --- /dev/null +++ b/backend/windmill-ai/src/vertex_workload_identity.rs @@ -0,0 +1,350 @@ +//! Vertex AI through Google Cloud Workload Identity Federation. +//! +//! A Vertex resource can name a workload identity pool provider instead of +//! carrying an access token. Windmill then mints an OIDC token for the caller, +//! exchanges it at Google's STS for a federated token and, when the resource names +//! a service account, impersonates it. The result is sent as the Vertex bearer +//! token, exactly as an `api_key` would be. + +use serde::Deserialize; +use windmill_common::client::AuthedClient; +use windmill_common::error::Error; + +use crate::ai_providers::AIProvider; +use crate::credentials::ProviderCredentials; + +pub const GCP_STS_TOKEN_URL: &str = "https://sts.googleapis.com/v1/token"; +pub const GCP_IAM_CREDENTIALS_URL: &str = "https://iamcredentials.googleapis.com/v1"; +const CLOUD_PLATFORM_SCOPE: &str = "https://www.googleapis.com/auth/cloud-platform"; + +/// Lifetime of the OIDC token presented to STS. It is only read once, at the +/// exchange, so there is no reason to let it outlive the access token it buys. +pub const VERTEX_OIDC_TOKEN_LIFETIME_SECS: i64 = 1800; + +/// The longest lifetime `generateAccessToken` grants without an organization +/// policy extending it. +const IMPERSONATED_TOKEN_LIFETIME_SECS: u64 = 3600; + +/// Exchange again this long before the access token expires, so a long streamed +/// response that starts on a reused token cannot outlive it. Capped at half the +/// token's lifetime so a short-lived token is not exchanged on every request. +const REFRESH_MARGIN: std::time::Duration = std::time::Duration::from_secs(300); + +/// The settings a Vertex resource authenticates with through Workload Identity +/// Federation. None of them is a secret: what authorises the exchange is the OIDC +/// token, and what it may do is the pool provider's and service account's policy. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct VertexWorkloadIdentity { + /// `projects//locations/global/workloadIdentityPools//providers/`. + pub provider: String, + /// The service account to impersonate. Without one, Vertex is called with the + /// federated token itself, which needs the pool's principals granted on the + /// project directly. + pub service_account_email: Option, + /// Audience of the OIDC token, for a provider configured with custom allowed + /// audiences. Defaults to the provider's own resource name, which is what a + /// provider accepts when none is configured. + pub audience: Option, +} + +impl VertexWorkloadIdentity { + /// The workload identity settings of a `vertex_ai_federated` resource, or `None` + /// for any other: only `workload_identity_provider` identifies one. Such a + /// resource is always on Vertex, so callers set the platform from the result. + pub fn from_resource( + provider: &AIProvider, + workload_identity_provider: Option<&str>, + service_account_email: Option<&str>, + audience: Option<&str>, + ) -> Result, Error> { + let non_empty = |v: Option<&str>| { + v.map(str::trim) + .filter(|v| !v.is_empty()) + .map(str::to_string) + }; + let Some(pool_provider) = non_empty(workload_identity_provider) else { + return Ok(None); + }; + if !matches!(provider, AIProvider::Anthropic | AIProvider::GoogleAI) { + return Err(Error::BadRequest(format!( + "A vertex_ai_federated resource can only be used for the Anthropic or Google AI \ + provider, not {provider:?}" + ))); + } + + let pool_provider = pool_provider + .trim_start_matches("https:") + .trim_start_matches("//iam.googleapis.com/") + .to_string(); + let segments: Vec<&str> = pool_provider.split('/').collect(); + let well_formed = matches!( + segments.as_slice(), + ["projects", p, "locations", l, "workloadIdentityPools", pool, "providers", name] + if [p, l, pool, name].iter().all(|s| !s.is_empty()) + ); + if !well_formed { + return Err(Error::BadRequest(format!( + "workload_identity_provider must be of the form \ + projects//locations/global/workloadIdentityPools//providers/, \ + got {pool_provider}" + ))); + } + + let service_account_email = non_empty(service_account_email); + if let Some(email) = service_account_email.as_deref() { + // It becomes a path segment of the impersonation URL. + let valid = email.contains('@') + && email + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '@' | '.' | '-' | '_')); + if !valid { + return Err(Error::BadRequest(format!( + "service_account_email is not a service account email: {email}" + ))); + } + } + + Ok(Some(Self { + provider: pool_provider, + service_account_email, + audience: non_empty(audience), + })) + } + + pub fn oidc_audience(&self) -> String { + self.audience + .clone() + .unwrap_or_else(|| format!("https://iam.googleapis.com/{}", self.provider)) + } +} + +/// The exchanged token is the identity of whoever uses the resource, not of +/// whoever wrote it, so it is only ever sent to Google: a resource author must not +/// be able to point another user's token at a host they read. +pub fn check_vertex_base_url(base_url: &str) -> Result<(), Error> { + let on_google = reqwest::Url::parse(base_url).is_ok_and(|url| { + url.scheme() == "https" + && url + .host_str() + .is_some_and(|host| host == "googleapis.com" || host.ends_with(".googleapis.com")) + }); + if on_google { + Ok(()) + } else { + Err(Error::BadRequest(format!( + "A Vertex AI resource that authenticates through workload_identity_provider must set \ + base_url to a https://*.googleapis.com Vertex endpoint, got {base_url:?}" + ))) + } +} + +/// A Google access token from a Workload Identity Federation exchange. +#[derive(Clone, Debug)] +pub struct GcpAccessToken { + pub access_token: String, + refresh_at: std::time::SystemTime, +} + +impl GcpAccessToken { + fn new(access_token: String, lifetime: std::time::Duration) -> Self { + // Google tokens live at most 12 hours; the clamp keeps an out-of-range + // `expires_in` from overflowing the clock arithmetic. + let lifetime = lifetime.min(std::time::Duration::from_secs(43200)); + let margin = REFRESH_MARGIN.min(lifetime / 2); + Self { access_token, refresh_at: std::time::SystemTime::now() + lifetime - margin } + } + + pub fn is_fresh(&self) -> bool { + std::time::SystemTime::now() < self.refresh_at + } +} + +#[derive(Deserialize)] +struct StsResponse { + access_token: String, + expires_in: u64, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct GenerateAccessTokenResponse { + access_token: String, +} + +/// Exchange an OIDC token for a Google access token: STS first, then the +/// service account impersonation when the resource names one. +pub async fn exchange_oidc_token( + identity: &VertexWorkloadIdentity, + subject_token: &str, +) -> Result { + let exchanged = request_access_token(identity, subject_token).await; + windmill_common::feature_usage::log_feature_usage( + "vertex_workload_identity", + "token_exchange", + if exchanged.is_ok() { "ok" } else { "failed" }, + ); + exchanged +} + +async fn request_access_token( + identity: &VertexWorkloadIdentity, + subject_token: &str, +) -> Result { + let http = &*windmill_common::utils::HTTP_CLIENT; + + let response = http + .post(GCP_STS_TOKEN_URL) + .form(&[ + ( + "grant_type", + "urn:ietf:params:oauth:grant-type:token-exchange", + ), + ("subject_token", subject_token), + ("subject_token_type", "urn:ietf:params:oauth:token-type:jwt"), + ( + "audience", + &format!("//iam.googleapis.com/{}", identity.provider), + ), + ( + "requested_token_type", + "urn:ietf:params:oauth:token-type:access_token", + ), + ("scope", CLOUD_PLATFORM_SCOPE), + ]) + .send() + .await + .map_err(|e| Error::internal_err(format!("Google STS token exchange failed: {e}")))?; + let federated = parse_response::(response, "Google STS token exchange").await?; + + let Some(email) = identity.service_account_email.as_deref() else { + return Ok(GcpAccessToken::new( + federated.access_token, + std::time::Duration::from_secs(federated.expires_in), + )); + }; + + let response = http + .post(format!( + "{GCP_IAM_CREDENTIALS_URL}/projects/-/serviceAccounts/{email}:generateAccessToken" + )) + .bearer_auth(&federated.access_token) + .json(&serde_json::json!({ + "scope": [CLOUD_PLATFORM_SCOPE], + "lifetime": format!("{IMPERSONATED_TOKEN_LIFETIME_SECS}s"), + })) + .send() + .await + .map_err(|e| { + Error::internal_err(format!("Impersonating service account {email} failed: {e}")) + })?; + let impersonated = parse_response::( + response, + &format!("Impersonating service account {email}"), + ) + .await?; + + Ok(GcpAccessToken::new( + impersonated.access_token, + std::time::Duration::from_secs(IMPERSONATED_TOKEN_LIFETIME_SECS), + )) +} + +async fn parse_response( + response: reqwest::Response, + what: &str, +) -> Result { + let status = response.status(); + if !status.is_success() { + let body = response.text().await.unwrap_or_default(); + return Err(Error::BadRequest(format!( + "{what} failed with status {status}: {body}" + ))); + } + response + .json::() + .await + .map_err(|e| Error::internal_err(format!("Failed to parse the {what} response: {e}"))) +} + +/// The Vertex access token of a federating resource for a job, reusing `cached` +/// while it is still fresh, so the agent loop exchanges once per job rather than +/// per turn. Returns `None` for a resource that does not federate. +pub async fn refresh_vertex_access_token<'a>( + credentials: &ProviderCredentials, + cached: &'a mut Option, + client: &AuthedClient, +) -> Result, Error> { + let Some(identity) = credentials.vertex_workload_identity.as_ref() else { + return Ok(None); + }; + check_vertex_base_url(&credentials.base_url)?; + if !cached.as_ref().is_some_and(GcpAccessToken::is_fresh) { + // A worker holds no OIDC signing key, so it asks the API to mint the token for this job. + let subject_token = client + .get_id_token_expiring_in( + &identity.oidc_audience(), + Some(VERTEX_OIDC_TOKEN_LIFETIME_SECS), + ) + .await + .map_err(|e| Error::ExecutionErr(format!("Failed to get an OIDC token: {e}")))?; + *cached = Some(exchange_oidc_token(identity, &subject_token).await?); + } + Ok(cached.as_ref().map(|token| token.access_token.as_str())) +} + +#[cfg(test)] +mod tests { + use super::*; + + const PROVIDER: &str = + "projects/123/locations/global/workloadIdentityPools/pool/providers/windmill"; + + fn vertex( + provider: Option<&str>, + email: Option<&str>, + ) -> Result, Error> { + VertexWorkloadIdentity::from_resource(&AIProvider::GoogleAI, provider, email, None) + } + + #[test] + fn provider_is_normalized_and_validated() { + for form in [ + PROVIDER.to_string(), + format!("//iam.googleapis.com/{PROVIDER}"), + format!("https://iam.googleapis.com/{PROVIDER}"), + ] { + let identity = vertex(Some(&form), None).unwrap().unwrap(); + assert_eq!(identity.provider, PROVIDER); + assert_eq!( + identity.oidc_audience(), + format!("https://iam.googleapis.com/{PROVIDER}") + ); + } + assert!(vertex(Some("projects/123/providers/windmill"), None).is_err()); + } + + #[test] + fn service_account_email_cannot_escape_its_path_segment() { + let sa = "vertex@my-project.iam.gserviceaccount.com"; + assert!(vertex(Some(PROVIDER), Some(sa)).is_ok()); + assert!(vertex(Some(PROVIDER), Some("a@b/../../other")).is_err()); + assert!(vertex(Some(PROVIDER), Some("a@b?x=1")).is_err()); + } + + #[test] + fn token_only_goes_to_google() { + assert!(check_vertex_base_url( + "https://us-east5-aiplatform.googleapis.com/v1/projects/p/locations/us-east5/publishers/anthropic/models" + ) + .is_ok()); + for url in [ + "http://us-east5-aiplatform.googleapis.com/v1", + "https://googleapis.com.evil.example/v1", + "https://evil-googleapis.com/v1", + "https://api.anthropic.com/v1", + "", + ] { + assert!(check_vertex_base_url(url).is_err(), "{url}"); + } + } +} diff --git a/backend/windmill-api-assets/tests/dbt_pinned_graph.rs b/backend/windmill-api-assets/tests/dbt_pinned_graph.rs index ac9b5b740c..eaa531dc4b 100644 --- a/backend/windmill-api-assets/tests/dbt_pinned_graph.rs +++ b/backend/windmill-api-assets/tests/dbt_pinned_graph.rs @@ -37,6 +37,7 @@ fn outsider() -> ApiAuthed { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index 1b53b546c4..889f1f09a0 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -171,6 +171,15 @@ impl AuthCache { // from a job's WM_TOKEN, even on an AUTH_CACHE hit whose cached authed // predates this field. opt_job_authed.authed.job_id = opt_job_authed.job_id; + // Read for each request, before any handler opens a transaction, so a check inside one + // never needs a second connection. Never cached with the login: the role caches it reads + // are the ones role changes clear. An unreadable role stays `None`, read again later. + if let Some(w_id) = w_id.as_deref() { + opt_job_authed.authed.capabilities = + windmill_common::roles::caller_capabilities(&self.db, w_id, &opt_job_authed.authed) + .await + .ok(); + } // The no-account rule is enforced here, once, for every guest request — not per // handler, where each guest-reachable route would have to remember it. Uncached, // so an account provisioned after the mint ends the guest session, and every @@ -348,6 +357,7 @@ impl AuthCache { job_id: None, credential_expiry: Some(credential_expiry), mcp_client: None, + capabilities: None, }; AUTH_CACHE.insert( key, @@ -394,6 +404,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: claims.mcp_client, + capabilities: None, }; // Fail closed: a `job_id` claim that does not parse must reject // the token rather than resolve to `None`, which would clear the @@ -526,6 +537,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }) } else { tracing::warn!( @@ -581,6 +593,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }) } else { tracing::warn!( @@ -681,6 +694,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }) } None if super_admin => { @@ -707,6 +721,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }), Err(e) => { tracing::error!( @@ -746,6 +761,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }) } None => None, @@ -767,6 +783,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }) } } @@ -808,6 +825,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }; Some(OptJobAuthed { authed, job_id: None }) } else { @@ -1183,6 +1201,7 @@ fn no_auth_admin_authed() -> ApiAuthed { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, } } diff --git a/backend/windmill-api-auth/src/composed.rs b/backend/windmill-api-auth/src/composed.rs index e9d79240dd..7860409c50 100644 --- a/backend/windmill-api-auth/src/composed.rs +++ b/backend/windmill-api-auth/src/composed.rs @@ -1,17 +1,60 @@ //! Authorizing what a restricted role composes: the references a value-only walk -//! (`check_flow_is_composition_only`) collects, checked against the caller's own permissions. +//! (`check_flow_is_composition_only`) collects, checked against the caller's own permissions, +//! and the Hub paths a trigger or schedule save names. use sqlx::{Postgres, Transaction}; use windmill_common::{ error::{self, Error}, flows::FlowValue, + jobs::{check_can_name_runnable, RunOrigin}, roles::AuthorLevel, + runnable_ref::RunnableRef, workspaces::{check_operator_can_build, BuilderKind}, DB, }; use crate::{get_scope_tags, is_super_admin_authed, ApiAuthed}; +/// The run-time rule for naming a Hub path, applied to one a builder saves. A save can hold many +/// Hub paths, so a refusal names the one it is about. +pub async fn check_builder_can_name_hub( + runnable: &RunnableRef, + authed: &ApiAuthed, + db: &DB, + w_id: &str, +) -> error::Result<()> { + let origin = RunOrigin::NamedBy(authed.to_authed_ref()); + check_can_name_runnable(&origin, runnable, db, w_id) + .await + .map_err(|e| name_refused_path(runnable, e)) +} + +fn name_refused_path(runnable: &RunnableRef, e: Error) -> Error { + match e { + Error::PermissionDenied(msg) => { + Error::PermissionDenied(format!("{}: {msg}", runnable.path())) + } + e => e, + } +} + +/// Refuses each of `new` that `old` does not hold and that needs `code`. A trigger or schedule +/// save is checked on the paths it changes only, so a member without `code` can still edit one +/// that already runs a Hub path; nothing is checked at fire. `old` must be the row locked by the +/// save, or a concurrent edit could slip a removed Hub path back in as unchanged. +pub async fn check_new_hub_paths( + new: &[RunnableRef], + old: &[RunnableRef], + authed: &ApiAuthed, + db: &DB, + w_id: &str, +) -> error::Result<()> { + for runnable in new.iter().filter(|r| !old.contains(r)) { + check_builder_can_name_hub(runnable, authed, db, w_id).await?; + } + Ok(()) +} + /// `validate_operator_composed_flow` on a transaction the caller already holds, so a write that /// has one open does not wait on a second connection. It must have been begun as the caller /// (`UserDB::begin`): its row-level security is the check. @@ -24,6 +67,9 @@ pub async fn authorize_composed_flow( w_id: &str, ) -> error::Result<()> { let mut refs = windmill_common::flows::check_flow_is_composition_only(value)?; + for runnable in &refs.hub_runnables { + check_builder_can_name_hub(runnable, authed, db, w_id).await?; + } // A builder links only an agent it can read, and binds only the tool inputs it leaves open. for agent in &refs.agents { diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index afddad0a6c..13ad961b86 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -29,6 +29,7 @@ use windmill_common::{ db::{Authable, Authed, AuthedRef}, error::{self, Error, Result}, jobs::JobTriggerKind, + roles::RoleCapabilities, triggers::TriggerMetadata, users::username_to_permissioned_as, workspaces::{check_operator_can_manage, ManageKind}, @@ -93,6 +94,9 @@ pub struct ApiAuthed { /// The OAuth client of an external issuer acting for this user (`mcp_external_idp`). /// Recorded on the runs it starts and handed to their steps as `WM_MCP_CLIENT`. pub mcp_client: Option, + /// The role's capabilities in the request's workspace (`AuthCache::get_opt_job_authed`); `None` + /// outside a request. + pub capabilities: Option, } impl ApiAuthed { @@ -106,6 +110,7 @@ impl ApiAuthed { folders: &self.folders, scopes: &self.scopes, token_prefix: &self.token_prefix, + capabilities: self.capabilities, } } @@ -161,6 +166,7 @@ impl From for Authed { scopes: value.scopes, token_prefix: value.token_prefix, mcp_client: value.mcp_client, + capabilities: value.capabilities, } } } @@ -183,6 +189,7 @@ impl From for ApiAuthed { job_id: None, credential_expiry: None, mcp_client: value.mcp_client, + capabilities: value.capabilities, } } } @@ -211,6 +218,10 @@ impl Authable for ApiAuthed { self.is_operator } + fn capabilities(&self) -> Option { + self.capabilities + } + fn groups(&self) -> &[String] { &self.groups } @@ -1166,6 +1177,7 @@ pub async fn fetch_api_authed_from_permissioned_as( job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }; API_AUTHED_CACHE.insert( diff --git a/backend/windmill-api-auth/src/scopes.rs b/backend/windmill-api-auth/src/scopes.rs index b5f082a6b4..2dffbeca51 100644 --- a/backend/windmill-api-auth/src/scopes.rs +++ b/backend/windmill-api-auth/src/scopes.rs @@ -105,6 +105,26 @@ pub fn check_route_access( )); } + // A CI test batch names flows and resources as well as scripts, and its handler checks + // each item against its own `:write` scope: the route needs write on one of them. + if route_suffix.as_deref() == Some("scripts/trigger_ci_tests_batch") + && token_scopes.iter().any(|s| { + ScopeDefinition::from_scope_string(s).is_ok_and(|scope| { + [ + ScopeDomain::Scripts, + ScopeDomain::Flows, + ScopeDomain::Resources, + ] + .into_iter() + .any(|d| { + scope_grants_access(&scope, d, ScopeAction::Write, None, None).unwrap_or(false) + }) + }) + }) + { + return Ok(()); + } + // tracing::error!("Checking route access {:?} {:?} {:?} {:?}", required_action, required_domain, required_kind, route_suffix); let mut is_scoped_token = false; // Check if any token scope grants the required access @@ -257,6 +277,7 @@ fn determine_kind_from_route(route_path: &str) -> Option { // still classified by their kind. if route_path.starts_with("jobs/run/preview") || route_path.starts_with("jobs/run_wait_result/preview") + || route_path.starts_with("jobs/run/flow_test/") { return None; } @@ -327,7 +348,7 @@ fn extract_domain_from_route( /// exports) and credential minting (`job_view_token`) are deliberately absent — those are /// `jobs:read`. Keep by-id read routes here in sync as they are added, or a run token /// loses the ability to follow its own run through them. -const RUN_WHITELISTED_GET_PATHS: [&'static str; 32] = [ +const RUN_WHITELISTED_GET_PATHS: [&'static str; 33] = [ "jobs_u/get_flow/", "jobs_u/get_root_job_id/", "jobs_u/get/", @@ -355,6 +376,7 @@ const RUN_WHITELISTED_GET_PATHS: [&'static str; 32] = [ "jobs/flow/user_states/", "jobs/job_signature/", "jobs/wac_approval_urls/", + "jobs/flow/approval_step_detail/", "jobs/completed/get/", "jobs/completed/get_result/", "jobs/completed/get_result_maybe/", @@ -437,8 +459,9 @@ pub fn has_raw_app_sdk_sentinel(scopes: Option<&[String]>) -> bool { /// so reaching one would make a captured SDK token a full account takeover. fn is_request_supplied_code_route(suffix: &str) -> bool { // Prefixes, so the `_async` variants are covered too. - const CODE_ROUTES: [&str; 10] = [ + const CODE_ROUTES: [&str; 11] = [ "jobs/run/preview", + "jobs/run/flow_test", "jobs/run_inline/preview", "jobs/run_wait_result/preview", "jobs/run/preview_bundle", @@ -552,7 +575,7 @@ fn resource_metadata_route_allowed(suffix: &str) -> bool { /// a direct `require_job_within_read_scope`. `jobs/result_by_id/` is absent because it /// resolves a node up through the enclosing flows, past the job the check admitted. /// A route added here without that check serves a path-scoped token every job. -const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 25] = [ +const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 26] = [ "jobs_u/get/", "jobs_u/get_logs/", "jobs_u/get_completed_logs_tail/", @@ -571,6 +594,7 @@ const READ_PATH_SCOPED_BY_ID_PATHS: [&'static str; 25] = [ "jobs_u/get_log_file/", "jobs_u/get_flow/", "jobs_u/flow/approval_info/", + "jobs/flow/approval_step_detail/", "jobs/run_progress/", "jobs/flow/user_states/", "jobs/completed/get/", @@ -1255,6 +1279,26 @@ mod tests { assert!(check_route_access(&scopes, "/api/w/test_workspace/jobs/123", "DELETE").is_err()); } + #[test] + fn ci_test_batch_route_takes_any_tested_kind_write_scope() { + let route = "/api/w/test/scripts/trigger_ci_tests_batch"; + for scope in ["flows:write:f/a/b", "resources:write", "scripts:write"] { + assert!( + check_route_access(&[scope.to_string()], route, "POST").is_ok(), + "{scope}" + ); + } + for scope in ["flows:read", "jobs:run", "apps:write"] { + assert!( + check_route_access(&[scope.to_string()], route, "POST").is_err(), + "{scope}" + ); + } + // The exemption is this route's alone. + let flows = vec!["flows:write".to_string()]; + assert!(check_route_access(&flows, "/api/w/test/scripts/create", "POST").is_err()); + } + #[test] fn data_metrics_is_its_own_domain_not_a_scripts_alias() { // `data_metrics` must be a distinct domain: a token scoped to it must reach @@ -1780,6 +1824,9 @@ mod tests { assert!(check_route_access(&["jobs:run:dependencies".into()], path, "POST").is_err()); } + // Replaces flow steps with code named by job id, as a preview does. + assert!(is_request_supplied_code_route("jobs/run/flow_test/f/x/y")); + // 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. for path in [ @@ -1788,6 +1835,7 @@ mod tests { "/api/w/ws/jobs/run/preview_flow", "/api/w/ws/jobs/run_wait_result/preview", "/api/w/ws/jobs/run_wait_result/preview_flow", + "/api/w/ws/jobs/run/flow_test/f/x/y", ] { assert_eq!( scope_for_route("POST", path).as_deref(), diff --git a/backend/windmill-api-configs/src/lib.rs b/backend/windmill-api-configs/src/lib.rs index 8336888088..debe879c26 100644 --- a/backend/windmill-api-configs/src/lib.rs +++ b/backend/windmill-api-configs/src/lib.rs @@ -35,6 +35,14 @@ pub fn global_service() -> Router { "/list_autoscaling_events/{worker_group}", get(list_autoscaling_events), ) + .route( + "/autoscaling_diagnostics/{worker_group}", + get(get_autoscaling_diagnostics), + ) + .route( + "/autoscaling_recording/{worker_group}", + post(set_autoscaling_recording), + ) .route("/test_autoscaling/{worker_group}", post(test_autoscaling)) .route( "/native_kubernetes_autoscaling_healthcheck", @@ -292,6 +300,7 @@ async fn update_config( }; let was_paused = is_set(previous.as_ref(), "paused"); let was_serving_dev = is_set(previous.as_ref(), "serves_dev_workspaces"); + let was_reserve = is_set(previous.as_ref(), "fairness_reserve"); sqlx::query!( "INSERT INTO config (name, config) VALUES ($1, $2) ON CONFLICT (name) DO UPDATE SET config = EXCLUDED.config", &name, @@ -329,6 +338,14 @@ async fn update_config( if serving_dev { "serve" } else { "stop" }, ); } + let reserve = is_set(Some(&config), "fairness_reserve"); + if reserve != was_reserve { + windmill_common::feature_usage::log_feature_usage( + "worker_group", + "fairness_reserve_toggle", + if reserve { "enable" } else { "disable" }, + ); + } } Ok(format!("Updated config {name}")) } @@ -401,6 +418,137 @@ async fn list_autoscaling_events( Ok(Json(events)) } +/// How long a recording of a worker group's autoscaling decisions lasts once started. It ends +/// by itself so it cannot be left on. +const AUTOSCALING_RECORDING_SECS: i64 = 24 * 60 * 60; + +/// The most recent decisions returned. A tick runs every 15-20s and decisions are kept 48h, +/// which is at most 11,520 of them. +const MAX_AUTOSCALING_DECISIONS: i64 = 12_000; + +#[derive(Serialize)] +struct AutoscalingDecision { + recorded_at: chrono::DateTime, + worker_count: i32, + occupancy_rate_15s: Option, + occupancy_rate_5m: Option, + occupancy_rate_30m: Option, + jobs_waiting: serde_json::Value, + decision: String, +} + +#[derive(Serialize)] +struct AutoscalingDiagnostics { + recording_until: Option>, + recording_started_by: Option, + decision_count: i64, + decisions: Vec, +} + +#[derive(Deserialize)] +struct AutoscalingDiagnosticsQuery { + include_decisions: Option, +} + +async fn get_autoscaling_diagnostics( + authed: ApiAuthed, + Extension(db): Extension, + Path(worker_group): Path, + Query(query): Query, +) -> error::JsonResult { + require_devops_role(&db, &authed).await?; + let recording = sqlx::query!( + "SELECT until, started_by FROM autoscaling_recording WHERE worker_group = $1 AND until > now()", + worker_group + ) + .fetch_optional(&db) + .await?; + let decision_count = sqlx::query_scalar!( + "SELECT count(*) AS \"count!\" FROM autoscaling_decision WHERE worker_group = $1", + worker_group + ) + .fetch_one(&db) + .await?; + if query.include_decisions == Some(false) { + return Ok(Json(AutoscalingDiagnostics { + recording_until: recording.as_ref().map(|r| r.until), + recording_started_by: recording.map(|r| r.started_by), + decision_count, + decisions: vec![], + })); + } + let mut decisions = sqlx::query_as!( + AutoscalingDecision, + "SELECT recorded_at, worker_count, occupancy_rate_15s, occupancy_rate_5m, occupancy_rate_30m, jobs_waiting, decision + FROM autoscaling_decision WHERE worker_group = $1 ORDER BY recorded_at DESC LIMIT $2", + worker_group, + MAX_AUTOSCALING_DECISIONS + ) + .fetch_all(&db) + .await?; + decisions.reverse(); + Ok(Json(AutoscalingDiagnostics { + recording_until: recording.as_ref().map(|r| r.until), + recording_started_by: recording.map(|r| r.started_by), + decision_count, + decisions, + })) +} + +#[derive(Deserialize)] +struct SetAutoscalingRecording { + record: bool, +} + +async fn set_autoscaling_recording( + authed: ApiAuthed, + Extension(db): Extension, + Path(worker_group): Path, + Json(body): Json, +) -> error::Result { + require_devops_role(&db, &authed).await?; + let mut tx = db.begin().await?; + if body.record { + sqlx::query!( + "INSERT INTO autoscaling_recording (worker_group, until, started_by) + VALUES ($1, now() + make_interval(secs => $2), $3) + ON CONFLICT (worker_group) DO UPDATE SET until = EXCLUDED.until, started_by = EXCLUDED.started_by", + worker_group, + AUTOSCALING_RECORDING_SECS as f64, + authed.email + ) + .execute(&mut *tx) + .await?; + } else { + sqlx::query!( + "DELETE FROM autoscaling_recording WHERE worker_group = $1", + worker_group + ) + .execute(&mut *tx) + .await?; + } + audit_log( + &mut *tx, + &authed, + if body.record { + "worker_config.autoscaling_recording_start" + } else { + "worker_config.autoscaling_recording_stop" + }, + ActionKind::Update, + "global", + Some(&worker_group), + None, + ) + .await?; + tx.commit().await?; + Ok(if body.record { + format!("Recording the autoscaling decisions of {worker_group} for 24h") + } else { + format!("Stopped recording the autoscaling decisions of {worker_group}") + }) +} + #[cfg(all(feature = "enterprise", feature = "private"))] async fn native_kubernetes_autoscaling_healthcheck( authed: ApiAuthed, diff --git a/backend/windmill-api-flows/src/flows.rs b/backend/windmill-api-flows/src/flows.rs index d4a4211f1c..6f9af28415 100644 --- a/backend/windmill-api-flows/src/flows.rs +++ b/backend/windmill-api-flows/src/flows.rs @@ -665,6 +665,7 @@ async fn create_flow( Extension(user_db): Extension, Extension(webhook): Extension, Path(w_id): Path, + Query(ci): Query, Json(mut nf): Json, ) -> Result<(StatusCode, String)> { let flows_level = @@ -967,7 +968,7 @@ async fn create_flow( ); // Trigger CI tests for items that reference this flow - { + if !ci.skip_ci_tests { let db2 = db.clone(); let w_id2 = w_id.clone(); let flow_path2 = nf.path.clone(); @@ -1281,6 +1282,7 @@ async fn update_flow( Extension(db): Extension, Extension(webhook): Extension, Path((w_id, flow_path)): Path<(String, StripPath)>, + Query(ci): Query, Json(ef): Json, ) -> Result { let flows_level = @@ -1785,7 +1787,7 @@ async fn update_flow( reregister_moved_native_triggers(&db, &authed, &w_id, moved_native_triggers); // Trigger CI tests for items that reference this flow - { + if !ci.skip_ci_tests { let db2 = db.clone(); let w_id2 = w_id.clone(); let flow_path2 = nf.path.clone(); @@ -2433,6 +2435,7 @@ mod tests { parallel: false, parallelism: None, squash: None, + iteration_label: None, }), stop_after_if: Some(StopAfterIf { expr: "previous.isEmpty()".to_string(), diff --git a/backend/windmill-api-groups/src/access.rs b/backend/windmill-api-groups/src/access.rs index b9f21a7bda..a74091958e 100644 --- a/backend/windmill-api-groups/src/access.rs +++ b/backend/windmill-api-groups/src/access.rs @@ -245,7 +245,18 @@ async fn fetch_target( name: &str, principal: &str, ) -> Result { - let email = match prefix { + let email = target_email(db, w_id, prefix, name).await?; + let mut target = fetch_authed_from_permissioned_as(principal, &email, w_id, db).await?; + // A workspace group and an instance group can share a name, and both come back. + target.groups.sort(); + target.groups.dedup(); + Ok(target) +} + +/// The principal's email, empty for a group. Not found when the principal does not exist, so +/// no route answers for a mistyped one as if it existed with no grants. +async fn target_email(db: &DB, w_id: &str, prefix: &str, name: &str) -> Result { + Ok(match prefix { "u" => { let usr = sqlx::query!( "SELECT email, disabled FROM usr WHERE workspace_id = $1 AND username = $2", @@ -284,13 +295,7 @@ async fn fetch_target( "principal must be u/ or g/".into(), )) } - }; - - let mut target = fetch_authed_from_permissioned_as(principal, &email, w_id, db).await?; - // A workspace group and an instance group can share a name, and both come back. - target.groups.sort(); - target.groups.dedup(); - Ok(target) + }) } async fn get_access( @@ -327,19 +332,19 @@ async fn get_access( .iter() .map(|f| f.0.clone()) .collect::>(); - let mut via = sqlx::query_as::<_, (String, Vec, Option)>( - "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k), - (extra_perms ->> $4)::boolean + let mut via = sqlx::query!( + "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\", + (extra_perms ->> $4)::boolean AS \"grant\" FROM folder WHERE workspace_id = $1 AND name = ANY($2)", + &w_id, + &folder_names, + &perms, + &principal ) - .bind(&w_id) - .bind(&folder_names) - .bind(&perms) - .bind(&principal) .fetch_all(&db) .await? .into_iter() - .map(|(name, via, grant)| (name, (via, grant))) + .map(|r| (r.name, (r.via, r.grant))) .collect::>(); let mut folders = target .folders @@ -386,14 +391,13 @@ async fn get_access( })) } -#[derive(Serialize, sqlx::FromRow)] +#[derive(Serialize)] struct BrowseFolder { name: String, /// The principal's own entry in the folder's `extra_perms`: absent, read (false) or write. grant: Option, /// Owners always keep write; `acls/add` refuses to lower it. target_owner: bool, - #[sqlx(skip)] #[serde(skip_serializing_if = "Option::is_none")] blocked: Option, } @@ -462,12 +466,14 @@ async fn browse_folders( .map(|(name, ..)| name.as_str()) .collect::>(); let mut tx = user_db.begin(&authed).await?; - let mut folders = sqlx::query_as::<_, BrowseFolder>( - "SELECT name, (extra_perms ->> $2)::boolean AS \"grant\", $2 = ANY(owners) AS target_owner + let mut folders = sqlx::query_as!( + BrowseFolder, + "SELECT name, (extra_perms ->> $2)::boolean AS \"grant\", + $2 = ANY(owners) AS \"target_owner!\", NULL::text AS blocked FROM folder WHERE workspace_id = $1 ORDER BY name", + &w_id, + &principal ) - .bind(&w_id) - .bind(&principal) .fetch_all(&mut *tx) .await?; tx.commit().await?; @@ -487,7 +493,8 @@ async fn browse_items( Path(w_id): Path, Query(q): Query, ) -> JsonResult { - check_principal(&authed, &q.principal)?; + let (prefix, name) = check_principal(&authed, &q.principal)?; + target_email(&db, &w_id, prefix, name).await?; let tables = ITEM_TABLES .iter() .filter(|(kind, ..)| { diff --git a/backend/windmill-api-integration-tests/tests/ai_routes.rs b/backend/windmill-api-integration-tests/tests/ai_routes.rs index 79152d82f7..c7f3900226 100644 --- a/backend/windmill-api-integration-tests/tests/ai_routes.rs +++ b/backend/windmill-api-integration-tests/tests/ai_routes.rs @@ -21,16 +21,29 @@ fn assert_2xx(status: u16, body: &str, endpoint: &str) { ); } -/// Start a mock AI API that echoes back a valid chat completion response. +/// Start a mock AI API answering a chat completion whose content is the request body it got. async fn start_mock_ai_api() -> u16 { - use axum::{routing::post, Json, Router}; + use axum::{response::IntoResponse, routing::post, Json, Router}; - let app = Router::new().fallback(post(|| async { + let app = Router::new().fallback(post(|body: String| async move { + let streams = + serde_json::from_str::(&body).is_ok_and(|v| v["stream"] == true); + if streams { + // OpenAI Responses API events, which `/ai/complete` reads. + let delta = json!({"type": "response.output_text.delta", "delta": body}); + let done = json!({"type": "response.completed", "response": {}}); + return ( + [("content-type", "text/event-stream")], + format!("data: {delta}\n\ndata: {done}\n\n"), + ) + .into_response(); + } Json(json!({ "id": "chatcmpl-test", "object": "chat.completion", - "choices": [{"message": {"role": "assistant", "content": "hello"}}] + "choices": [{"message": {"role": "assistant", "content": body}}] })) + .into_response() })); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); @@ -81,32 +94,119 @@ async fn test_ai_proxy_endpoints(db: Pool) -> anyhow::Result<()> { "providers": { "openai": { "resource_path": "f/ai/openai_config", - "models": ["gpt-4"] + "models": ["gpt-4", "gpt-3.5-turbo"] } - } + }, + "default_model": {"provider": "openai", "model": "gpt-4/thinking"}, + "max_tokens_per_model": {"openai:gpt-4": 100} })) .execute(&db) .await?; - // POST /w/{ws}/ai/proxy/chat/completions - let resp = authed( - client() - .post(format!( - "http://localhost:{port}/api/w/test-workspace/ai/proxy/chat/completions" - )) - .header("X-Provider", "openai") - .json(&json!({ - "model": "gpt-4", - "messages": [{"role": "user", "content": "hi"}] - })), + let proxy = |body: &'static str| { + authed( + client() + .post(format!( + "http://localhost:{port}/api/w/test-workspace/ai/proxy/chat/completions" + )) + .header("X-Provider", "openai") + .header("Content-Type", "application/json") + .body(body), + ) + .send() + }; + let complete = |body: serde_json::Value| { + authed( + client() + .post(format!( + "http://localhost:{port}/api/w/test-workspace/ai/complete" + )) + .json(&body), + ) + .send() + }; + + // An enabled model with no token limit reaches upstream byte for byte. + let sent = r#"{ "messages": [{"role": "user", "content": "hi"}], "model": "gpt-3.5-turbo" }"#; + let resp = proxy(sent).await?; + let status = resp.status().as_u16(); + let body = resp.text().await?; + assert_2xx(status, &body, "POST /ai/proxy/chat/completions"); + let received: serde_json::Value = serde_json::from_str(&body)?; + assert_eq!(received["choices"][0]["message"]["content"], sent); + + // A limited model's output is capped, in the field the provider reads. + let resp = proxy( + r#"{"model": "gpt-4", "max_completion_tokens": 5000, "max_output_tokens": 9000, "messages": []}"#, ) - .send() .await?; + let status = resp.status().as_u16(); + let body = resp.text().await?; assert_2xx( - resp.status().as_u16(), - &resp.text().await?, - "POST /ai/proxy/chat/completions", + status, + &body, + "POST /ai/proxy/chat/completions with a limit", ); + let received: serde_json::Value = serde_json::from_str(&body)?; + let upstream: serde_json::Value = serde_json::from_str( + received["choices"][0]["message"]["content"] + .as_str() + .unwrap(), + )?; + assert_eq!( + upstream["max_completion_tokens"], 100, + "upstream got: {upstream}" + ); + assert!( + upstream.get("max_output_tokens").is_none(), + "upstream got: {upstream}" + ); + + // The workspace's key is not spent on a model the admin has not enabled. + let resp = + proxy(r#"{"model": "gpt-4o", "messages": [{"role": "user", "content": "hi"}]}"#).await?; + assert_eq!(resp.status().as_u16(), 400, "proxy: {}", resp.text().await?); + let resp = complete(json!({ + "system": "s", + "user": "hi", + "model": {"provider": "openai", "model": "gpt-4o"} + })) + .await?; + assert_eq!( + resp.status().as_u16(), + 400, + "complete: {}", + resp.text().await? + ); + + // A legacy `/thinking` default runs as the model without the suffix. + let resp = complete(json!({"system": "s", "user": "hi"})).await?; + let status = resp.status().as_u16(); + let body = resp.text().await?; + assert_2xx(status, &body, "POST /ai/complete with the default model"); + let text = serde_json::from_str::(&body)?["text"] + .as_str() + .unwrap_or_default() + .to_string(); + let upstream: serde_json::Value = serde_json::from_str(&text)?; + assert_eq!(upstream["model"], "gpt-4", "upstream got: {text}"); + + let resp = complete(json!({ + "system": "s", + "user": "hi", + "model": {"provider": "openai", "model": "gpt-4"}, + "max_tokens": 5000 + })) + .await?; + let status = resp.status().as_u16(); + let body = resp.text().await?; + assert_2xx(status, &body, "POST /ai/complete with a larger max_tokens"); + let text = serde_json::from_str::(&body)?["text"] + .as_str() + .unwrap_or_default() + .to_string(); + let upstream: serde_json::Value = serde_json::from_str(&text)?; + assert_eq!(upstream["max_output_tokens"], 100, "upstream got: {text}"); Ok(()) } @@ -295,7 +395,10 @@ async fn test_ai_proxy_x_resource_value(db: Pool) -> anyhow::Result<() ); let resp = send("sk-other", "SECRET_TOKEN").await?; - assert!(resp.status().as_u16() >= 400, "a different key must reach the upstream as is"); + assert!( + resp.status().as_u16() >= 400, + "a different key must reach the upstream as is" + ); let resp = send("$var:u/test-user/secret", "SCOPED_AI_TOKEN").await?; let body = resp.text().await?; diff --git a/backend/windmill-api-integration-tests/tests/drafts.rs b/backend/windmill-api-integration-tests/tests/drafts.rs index 0d1e3c9185..35bee45682 100644 --- a/backend/windmill-api-integration-tests/tests/drafts.rs +++ b/backend/windmill-api-integration-tests/tests/drafts.rs @@ -127,6 +127,50 @@ async fn test_update_draft_conflict_lifecycle(db: Pool) -> anyhow::Res Ok(()) } +/// `/drafts/list` types a resource draft by the deployed row, which a deploy keeps, else by the +/// draft: what lets every listing tell an agent's draft apart without reading it. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_list_drafts_resource_type(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let c = client_for("SECRET_TOKEN"); + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, extra_perms, created_by) \ + VALUES ('test-workspace', 'u/test-user/pg', '{}'::jsonb, 'postgresql', '{}', 'test-user')", + ) + .execute(&db) + .await?; + for (path, rt) in [ + ("u/test-user/pg", "ai_agent"), + ("u/test-user/agent", "ai_agent"), + ] { + let value = json!({ "path": path, "resource_type": rt, "description": "d", "args": {} }); + let r = c + .post(save_url(port, "resource", path)) + .json(&json!({ "value": value })) + .send() + .await?; + assert_eq!(r.status(), 200, "save {path}"); + } + + let rows: Vec = c + .get(format!("http://localhost:{port}/api/w/{WS}/drafts/list")) + .send() + .await? + .json() + .await?; + let typed = |path: &str| { + rows.iter() + .find(|r| r["path"] == path) + .map(|r| (r["resource_type"].clone(), r["summary"].clone())) + .unwrap() + }; + assert_eq!(typed("u/test-user/pg"), (json!("postgresql"), json!(null))); + assert_eq!(typed("u/test-user/agent"), (json!("ai_agent"), json!("d"))); + Ok(()) +} + /// require_can_write_path: own namespace allowed, another user's namespace /// rejected, operators rejected outright. #[sqlx::test(migrations = "../migrations", fixtures("base"))] @@ -311,3 +355,339 @@ async fn test_cross_user_draft_privacy(db: Pool) -> anyhow::Result<()> Ok(()) } + +/// Moving a session's drafts into a fork is all-or-nothing: a draft the caller already has in +/// the fork blocks the whole transfer rather than one side silently winning, unless the caller +/// asks to replace it, and the source copy is removed only together with a successful copy. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_transfer_drafts_to_fork(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let c = client_for("SECRET_TOKEN"); + let me = "test@windmill.dev"; + let fork = "wm-fork-transfer"; + let transfer_url = format!("http://localhost:{port}/api/w/{WS}/drafts/transfer"); + let fork_count = |path: &'static str| { + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM draft WHERE workspace_id = $1 AND path = $2 AND email = $3", + ) + .bind(fork) + .bind(path) + .bind(me) + .fetch_one(&db) + }; + + let r = c + .post(save_url(port, "script", "u/test-user/a")) + .json(&json!({ "value": { "content": "a" } })) + .send() + .await?; + assert_eq!(r.status(), 200); + let r = c + .post(format!( + "http://localhost:{port}/api/w/{WS}/workspaces/create_fork" + )) + .json(&json!({ "id": fork, "name": "transfer" })) + .send() + .await?; + assert!(r.status().is_success(), "create fork: {}", r.text().await?); + // Created after the fork, so only the source has it. + let r = c + .post(save_url(port, "script", "u/test-user/b")) + .json(&json!({ "value": { "content": "b" } })) + .send() + .await?; + assert_eq!(r.status(), 200); + + let items = json!([ + { "kind": "script", "path": "u/test-user/a" }, + { "kind": "script", "path": "u/test-user/b" } + ]); + + // A token bound to the source authenticates on its routes but must not write the fork. + sqlx::query( + "INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin, workspace_id) + VALUES (encode(sha256('BOUND_TOKEN'::bytea), 'hex'), 'BOUND_TOK', 'BOUND_TOKEN', $1, 'bound', true, $2)", + ) + .bind(me) + .bind(WS) + .execute(&db) + .await?; + let r = client_for("BOUND_TOKEN") + .post(&transfer_url) + .json(&json!({ "target_workspace": fork, "items": items })) + .send() + .await?; + assert_eq!(r.status(), 403); + assert_eq!(fork_count("u/test-user/b").await?, 0); + + // A JWT has no `token` row: its own claims decide which workspaces it reaches. + set_jwt_secret().await; + let jwt = |workspace_ids: Vec<&str>, job_id: Option<&str>, is_admin: bool| { + windmill_common::jwt::encode_with_internal_secret(windmill_common::auth::JWTAuthClaims { + email: me.to_string(), + username: "test-user".to_string(), + is_admin, + is_operator: false, + groups: vec![], + folders: vec![], + label: None, + workspace_id: None, + workspace_ids: Some(workspace_ids.into_iter().map(String::from).collect()), + exp: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as usize + + 3600, + job_id: job_id.map(String::from), + scopes: None, + audit_span: None, + mcp_client: None, + }) + }; + let job_id = uuid::Uuid::new_v4().to_string(); + let r = c + .post(save_url(port, "script", "u/someone-else/x")) + .json(&json!({ "value": { "content": "x" } })) + .send() + .await?; + assert_eq!(r.status(), 200); + for (claims, path, status) in [ + (jwt(vec![WS], None, true).await?, "u/test-user/a", 403), + ( + jwt(vec![WS, fork], Some(&job_id), true).await?, + "u/test-user/a", + 403, + ), + (jwt(vec![WS, fork], None, true).await?, "u/test-user/a", 200), + // An admin in the fork's database, but the JWT does not claim it: the claims win. + ( + jwt(vec![WS, fork], None, false).await?, + "u/someone-else/x", + 401, + ), + ] { + let r = client_for(&format!("jwt_{claims}")) + .post(&transfer_url) + .json( + &json!({ "target_workspace": fork, "items": [{ "kind": "script", "path": path }] }), + ) + .send() + .await?; + assert_eq!(r.status(), status, "{path}: {}", r.text().await?); + } + assert_eq!(fork_count("u/someone-else/x").await?, 0); + + // `a` was cloned into the fork: the whole transfer is refused and nothing moves. + let body: serde_json::Value = c + .post(&transfer_url) + .json(&json!({ "target_workspace": fork, "items": items, "remove_from_source": true })) + .send() + .await? + .json() + .await?; + assert_eq!( + body["conflicts"], + json!([{ "kind": "script", "path": "u/test-user/a" }]) + ); + assert_eq!(fork_count("u/test-user/b").await?, 0); + assert_eq!(draft_count(&db, "u/test-user/a", "script", me).await, 1); + assert_eq!(draft_count(&db, "u/test-user/b", "script", me).await, 1); + + // A save after the clone: replacing the clone's copy must carry it into the fork. + let r = c + .post(save_url(port, "script", "u/test-user/a")) + .json(&json!({ "value": { "content": "a2" } })) + .send() + .await?; + assert_eq!(r.status(), 200); + let body: serde_json::Value = c + .post(&transfer_url) + .json(&json!({ + "target_workspace": fork, "items": items, + "remove_from_source": true, "replace_existing": true + })) + .send() + .await? + .json() + .await?; + assert_eq!(body["conflicts"], json!([])); + assert_eq!(body["copied"].as_array().unwrap().len(), 2); + assert_eq!(body["removed"].as_array().unwrap().len(), 2); + assert_eq!(fork_count("u/test-user/a").await?, 1); + assert_eq!(fork_count("u/test-user/b").await?, 1); + let a_in_fork: String = sqlx::query_scalar( + "SELECT value->>'content' FROM draft WHERE workspace_id = $1 AND path = 'u/test-user/a'", + ) + .bind(fork) + .fetch_one(&db) + .await?; + assert_eq!(a_in_fork, "a2"); + assert_eq!(draft_count(&db, "u/test-user/a", "script", me).await, 0); + assert_eq!(draft_count(&db, "u/test-user/b", "script", me).await, 0); + + // With nothing left in the source to replace them, the fork's drafts stay. + let r = c + .post(&transfer_url) + .json(&json!({ + "target_workspace": fork, "items": items, + "remove_from_source": true, "replace_existing": true + })) + .send() + .await?; + assert_eq!(r.status(), 200); + assert_eq!(fork_count("u/test-user/a").await?, 1); + assert_eq!(fork_count("u/test-user/b").await?, 1); + + // An app policy naming someone who is not a member of the fork is re-pointed at the user, as + // the fork's own clone does: a deploy in the fork rejects an identity that does not resolve. + let r = c + .post(save_url(port, "raw_app", "u/test-user/app")) + .json(&json!({ "value": { "policy": { + "on_behalf_of": "u/not-in-fork", "on_behalf_of_email": "ghost@windmill.dev" + } } })) + .send() + .await?; + assert_eq!(r.status(), 200, "{}", r.text().await?); + let r = c + .post(&transfer_url) + .json(&json!({ + "target_workspace": fork, + "items": [{ "kind": "raw_app", "path": "u/test-user/app" }] + })) + .send() + .await?; + assert_eq!(r.status(), 200, "{}", r.text().await?); + let on_behalf_of: String = sqlx::query_scalar( + "SELECT value->'policy'->>'on_behalf_of' FROM draft + WHERE workspace_id = $1 AND path = 'u/test-user/app'", + ) + .bind(fork) + .fetch_one(&db) + .await?; + assert_eq!(on_behalf_of, "u/test-user"); + + // A script version the fork does not have (deployed in the source after the fork was made) + // is no lineage there: a deploy naming it as parent would be refused. + let r = c + .post(save_url(port, "script", "u/test-user/lineage")) + .json(&json!({ "value": { "content": "l", "parent_hash": "0123456789abcdef" } })) + .send() + .await?; + assert_eq!(r.status(), 200, "{}", r.text().await?); + let r = c + .post(&transfer_url) + .json(&json!({ + "target_workspace": fork, + "items": [{ "kind": "script", "path": "u/test-user/lineage" }] + })) + .send() + .await?; + assert_eq!(r.status(), 200, "{}", r.text().await?); + let (parent_hash, base): (Option, Option) = sqlx::query_as( + "SELECT value->>'parent_hash', base FROM draft + WHERE workspace_id = $1 AND path = 'u/test-user/lineage'", + ) + .bind(fork) + .fetch_one(&db) + .await?; + assert_eq!((parent_hash, base), (None, None)); + + // A version the fork has keeps its lineage. Its hash has the high bit set, so the match also + // holds for a negative i64, which serializes as 16 hex digits. + sqlx::query( + "INSERT INTO script (workspace_id, hash, path, summary, description, content, created_by) + VALUES ($1, -1, 'u/test-user/lineage', '', '', 'l', 'test-user')", + ) + .bind(fork) + .execute(&db) + .await?; + let r = c + .post(save_url(port, "script", "u/test-user/lineage")) + .json(&json!({ "value": { "content": "l2", "parent_hash": "ffffffffffffffff" } })) + .send() + .await?; + assert_eq!(r.status(), 200, "{}", r.text().await?); + let r = c + .post(&transfer_url) + .json(&json!({ + "target_workspace": fork, + "items": [{ "kind": "script", "path": "u/test-user/lineage" }], + "replace_existing": true + })) + .send() + .await?; + assert_eq!(r.status(), 200, "{}", r.text().await?); + let (parent_hash, base): (Option, Option) = sqlx::query_as( + "SELECT value->>'parent_hash', base FROM draft + WHERE workspace_id = $1 AND path = 'u/test-user/lineage'", + ) + .bind(fork) + .fetch_one(&db) + .await?; + assert_eq!( + (parent_hash.as_deref(), base.as_deref()), + (Some("ffffffffffffffff"), Some("ffffffffffffffff")) + ); + + // Any workspace of the family takes them: here back from the fork to its parent. + let r = c + .post(format!( + "http://localhost:{port}/api/w/{fork}/drafts/transfer" + )) + .json(&json!({ + "target_workspace": WS, + "items": [{ "kind": "script", "path": "u/test-user/a" }], + "remove_from_source": true + })) + .send() + .await?; + assert_eq!(r.status(), 200, "{}", r.text().await?); + assert_eq!(draft_count(&db, "u/test-user/a", "script", me).await, 1); + assert_eq!(fork_count("u/test-user/a").await?, 0); + + // A workspace outside the family is refused. + let r = c + .post(&transfer_url) + .json(&json!({ "target_workspace": "admins", "items": items })) + .send() + .await?; + assert_eq!(r.status(), 400); + + // A pipeline node based on a version the target lacks would fail Deploy all there: refused, + // and the source keeps it. One based on a version the target has moves. + let pipeline = |hash: &str| json!({ "drafts": [["f/p/n", { "localId": "n", "script": { "path": "f/p/n", "hash": hash } }]] }); + for (path, hash) in [ + ("f/p_stale", "00000000000abcde"), + ("f/p_ok", "ffffffffffffffff"), + ] { + sqlx::query( + "INSERT INTO draft (workspace_id, path, typ, value, email) VALUES ($1, $2, 'data_pipeline', $3, $4)", + ) + .bind(WS) + .bind(path) + .bind(pipeline(hash)) + .bind(me) + .execute(&db) + .await?; + } + let move_pipeline = |path: &'static str| { + c.post(&transfer_url) + .json(&json!({ + "target_workspace": fork, + "items": [{ "kind": "data_pipeline", "path": path }], + "remove_from_source": true + })) + .send() + }; + let r = move_pipeline("f/p_stale").await?; + assert_eq!(r.status(), 400, "{}", r.text().await?); + assert_eq!(draft_count(&db, "f/p_stale", "data_pipeline", me).await, 1); + assert_eq!(fork_count("f/p_stale").await?, 0); + let r = move_pipeline("f/p_ok").await?; + assert_eq!(r.status(), 200, "{}", r.text().await?); + assert_eq!(fork_count("f/p_ok").await?, 1); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/native_triggers.rs b/backend/windmill-api-integration-tests/tests/native_triggers.rs index e05a1f1ed5..327c9ab9b9 100644 --- a/backend/windmill-api-integration-tests/tests/native_triggers.rs +++ b/backend/windmill-api-integration-tests/tests/native_triggers.rs @@ -68,6 +68,7 @@ fn test_authed() -> ApiAuthed { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } @@ -484,6 +485,7 @@ async fn test_require_native_integration_use_needs_code_and_manage_triggers( operator.username = "operator".to_string(); operator.is_admin = false; operator.is_operator = true; + operator.capabilities = None; assert!( require_native_integration_use(&db, "test-workspace", &operator) .await diff --git a/backend/windmill-api-integration-tests/tests/offboarding.rs b/backend/windmill-api-integration-tests/tests/offboarding.rs index 8dc8079096..ce5d0578ca 100644 --- a/backend/windmill-api-integration-tests/tests/offboarding.rs +++ b/backend/windmill-api-integration-tests/tests/offboarding.rs @@ -321,6 +321,86 @@ async fn test_offboard_to_folder(db: Pool) -> anyhow::Result<()> { Ok(()) } +/// Offboarding moves the user's runnables to the target, so handlers naming them must follow. +#[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))] +async fn test_offboard_moves_handler_paths(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::raw_sql( + r#"UPDATE schedule SET on_failure = 'script/u/test-user-2/script_a', on_success = 'flow/u/test-user-2/flow_a' + WHERE workspace_id = 'test-workspace' AND path = 'f/test-folder/sched_shared'; + UPDATE http_trigger SET error_handler_path = 'u/test-user-2/script_b' + WHERE workspace_id = 'test-workspace' AND path = 'f/test-folder/webhook_shared'; + UPDATE workspace_settings SET error_handler = '{"path": "script/u/test-user-2/script_b", "muted_on_cancel": true}', + slack_command_script = 'u/test-user-2/script_a', teams_command_script = 'flow/u/test-user-2/flow_a', + default_app = 'u/test-user-2/app_a' + WHERE workspace_id = 'test-workspace';"#, + ) + .execute(&db) + .await?; + + let resp = authed(client().post(ws_url(port, "offboard/test-user-2"))) + .json(&json!({ + "reassign_to": "f/test-folder", + "new_on_behalf_of_user": "test-user", + "delete_user": true + })) + .send() + .await?; + assert_eq!(resp.status(), 200, "offboard: {}", resp.text().await?); + + let schedule: (String, String) = sqlx::query_as( + "SELECT on_failure, on_success FROM schedule + WHERE workspace_id = 'test-workspace' AND path = 'f/test-folder/sched_shared'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + schedule, + ( + "script/f/test-folder/script_a".into(), + "flow/f/test-folder/flow_a".into() + ) + ); + + let trigger: String = sqlx::query_scalar( + "SELECT error_handler_path FROM http_trigger + WHERE workspace_id = 'test-workspace' AND path = 'f/test-folder/webhook_shared'", + ) + .fetch_one(&db) + .await?; + assert_eq!(trigger, "f/test-folder/script_b"); + + let error_handler: serde_json::Value = sqlx::query_scalar( + "SELECT error_handler FROM workspace_settings WHERE workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + error_handler, + json!({ "path": "script/f/test-folder/script_b", "muted_on_cancel": true }) + ); + + let commands: (String, String, String) = sqlx::query_as( + "SELECT slack_command_script, teams_command_script, default_app FROM workspace_settings + WHERE workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + commands, + ( + "f/test-folder/script_a".into(), + "flow/f/test-folder/flow_a".into(), + "f/test-folder/app_a".into() + ) + ); + + Ok(()) +} + #[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))] async fn test_offboard_reassign_only(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; 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 index 43342907d6..3564cfccd1 100644 --- a/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs +++ b/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs @@ -106,6 +106,7 @@ async fn test_preview_on_behalf_of(db: Pool) -> anyhow::Result<()> { scopes: None, token_prefix: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), }, "test-workspace", 3600, diff --git a/backend/windmill-api-integration-tests/tests/raw_app_static_input_references.rs b/backend/windmill-api-integration-tests/tests/raw_app_static_input_references.rs new file mode 100644 index 0000000000..3698baf17a --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/raw_app_static_input_references.rs @@ -0,0 +1,77 @@ +use serde_json::json; +use sqlx::{Pool, Postgres}; + +/// The migration has already run against the empty test database, so the test plants the +/// earlier shape and re-executes it, twice, to also pin that a second run changes nothing. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn raw_app_policy_static_inputs_are_references(db: Pool) -> anyhow::Result<()> { + // App 910's value holds NUL escapes, which jsonb refuses, and a literal `\\u0000`. + sqlx::raw_sql( + r#" + INSERT INTO app (id, workspace_id, path, policy, versions) VALUES (900, 'test-workspace', 'u/test-user/raw', '{ + "execution_mode": "anonymous", + "triggerables_v2": { + "orders:rawscript/abc": {"static_inputs": {"pw": "plain", "db": {"host": "h"}, "note": "edited", "same": "$var:u/test-user/same"}}, + "lookup:script/u/test-user/s": {"static_inputs": {"pw": "plain", "key": "plain"}}, + "orders:preview:rawscript/def": {"static_inputs": {"pw": "public"}}, + "orders:script/preview:rawscript/fed": {"static_inputs": {"pw": "public"}} + }}', '{901}'); + INSERT INTO app_version (id, app_id, value, created_by, raw_app) VALUES (901, 900, '{"runnables": { + "orders": {"type": "inline", "fields": { + "pw": {"type": "static", "value": "$var:u/test-user/pw"}, + "db": {"type": "static", "value": "$res:u/test-user/db"}, + "note": {"type": "static", "value": "hello"}, + "same": {"type": "static", "value": "$var:u/test-user/same"}, + "asked": {"type": "user", "value": "$var:u/test-user/pw"}}}, + "lookup": {"type": "path", "fields": {"pw": {"type": "user", "value": "$var:u/test-user/pw"}, + "key": {"type": "static", "value": "$jsonvar:u/test-user/key"}}}, + "orders:preview": {"type": "inline", "fields": {"pw": {"type": "static", "value": "public"}}}, + "orders:script/preview": {"type": "inline", "fields": {"pw": {"type": "static", "value": "public"}}}}}', 'test-user', true); + + INSERT INTO app (id, workspace_id, path, policy, versions) VALUES (910, 'test-workspace', 'u/test-user/nul', + '{"triggerables_v2": {"orders:rawscript/abc": {"static_inputs": {"pw": "plain"}}}}', '{911}'); + INSERT INTO app_version (id, app_id, value, created_by, raw_app) VALUES (911, 910, '{ + "files": {"/.DS_Store": "\u0000\u0000\u0001Bud1\\u0000"}, + "runnables": {"orders": {"fields": {"pw": {"type": "static", "value": "$var:u/test-user/pw"}}}}}', + 'test-user', true); + + INSERT INTO app (id, workspace_id, path, policy, versions) VALUES (920, 'test-workspace', 'u/test-user/control', + '{"triggerables_v2": {"orders:rawscript/abc": {"static_inputs": {"note": "edited"}}}}', '{921}'); + INSERT INTO app_version (id, app_id, value, created_by, raw_app) VALUES (921, 920, + '{"runnables": {"orders": {"fields": {"note": {"type": "static", "value": "hello"}}}}}', 'test-user', true); + "#, + ) + .execute(&db) + .await?; + + for _ in 0..2 { + sqlx::raw_sql(include_str!( + "../../migrations/20261113164906_raw_app_policy_static_input_references.up.sql" + )) + .execute(&db) + .await?; + } + + let policies: Vec = sqlx::query_scalar( + "SELECT policy->'triggerables_v2' FROM app WHERE id IN (900, 910, 920) ORDER BY id", + ) + .fetch_all(&db) + .await?; + assert_eq!( + policies, + [ + json!({ + "orders:rawscript/abc": {"static_inputs": { + "pw": "$var:u/test-user/pw", "db": "$res:u/test-user/db", + "note": "edited", "same": "$var:u/test-user/same"}}, + "lookup:script/u/test-user/s": {"static_inputs": {"pw": "plain", "key": "$jsonvar:u/test-user/key"}}, + "orders:preview:rawscript/def": {"static_inputs": {"pw": "public"}}, + "orders:script/preview:rawscript/fed": {"static_inputs": {"pw": "public"}} + }), + json!({"orders:rawscript/abc": {"static_inputs": {"pw": "$var:u/test-user/pw"}}}), + json!({"orders:rawscript/abc": {"static_inputs": {"note": "edited"}}}), + ] + ); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/resources.rs b/backend/windmill-api-integration-tests/tests/resources.rs index ebca295339..9f465eed26 100644 --- a/backend/windmill-api-integration-tests/tests/resources.rs +++ b/backend/windmill-api-integration-tests/tests/resources.rs @@ -760,6 +760,127 @@ async fn test_resource_cache_handles_job_context(db: Pool) -> anyhow:: Ok(()) } +/// The installation serves a non-admin only the URL an admin last saved on an +/// app-backed resource, so a write by anyone else must never set it, and a new +/// resource where an approved one used to be must not inherit it. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_github_app_repo_approval_follows_admin_writes( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base = format!( + "http://localhost:{}/api/w/test-workspace/resources", + server.addr.port() + ); + let (path, renamed) = ("u/test-user-2/repo", "u/test-user-2/repo2"); + let (approved, other) = ( + "https://github.com/o/r.git", + "https://github.com/o/other.git", + ); + let value = |url: &str| json!({"value": {"url": url, "is_github_app": true}}); + let create = |url: &str| { + let mut body = value(url); + body["path"] = json!(path); + body["resource_type"] = json!("git_repository"); + body + }; + let post = |token: &'static str, url: String, body: serde_json::Value| async move { + let resp = client() + .post(url) + .bearer_auth(token) + .json(&body) + .send() + .await + .unwrap(); + assert!(resp.status().is_success(), "{}", resp.text().await.unwrap()); + }; + let approved_url = |path: &'static str| { + let db = db.clone(); + async move { + sqlx::query_scalar::<_, String>( + "SELECT url FROM github_app_repo_approval + WHERE workspace_id = 'test-workspace' AND path = $1", + ) + .bind(path) + .fetch_optional(&db) + .await + .unwrap() + } + }; + + post("SECRET_TOKEN_2", format!("{base}/create"), create(approved)).await; + assert_eq!( + approved_url(path).await, + None, + "a non-admin's write approves nothing" + ); + + // Only a save of the value approves: an admin renaming or describing a + // resource has not looked at its URL. + post( + "SECRET_TOKEN", + format!("{base}/update/{path}"), + json!({"description": "ok"}), + ) + .await; + assert_eq!(approved_url(path).await, None); + let mut save = value(approved); + save["description"] = json!("ok"); + post("SECRET_TOKEN", format!("{base}/update/{path}"), save).await; + assert_eq!(approved_url(path).await.as_deref(), Some(approved)); + + post( + "SECRET_TOKEN_2", + format!("{base}/update_value/{path}"), + value(other), + ) + .await; + assert_eq!(approved_url(path).await.as_deref(), Some(approved)); + + post( + "SECRET_TOKEN", + format!("{base}/update_value/{path}"), + value(other), + ) + .await; + assert_eq!(approved_url(path).await.as_deref(), Some(other)); + + post( + "SECRET_TOKEN_2", + format!("{base}/update/{path}"), + json!({"path": renamed}), + ) + .await; + assert_eq!(approved_url(renamed).await.as_deref(), Some(other)); + post("SECRET_TOKEN_2", format!("{base}/create"), create(other)).await; + assert_eq!( + approved_url(path).await, + None, + "nothing is inherited from the old path" + ); + + // An admin save that names no app-backed repository revokes the old one, so a + // non-admin cannot put the earlier URL back and be served it. + post( + "SECRET_TOKEN", + format!("{base}/update_value/{renamed}"), + json!({"value": {"url": other, "is_github_app": false}}), + ) + .await; + assert_eq!(approved_url(renamed).await, None); + + // A `$var:` resolves to whatever its owner sets, so it is never approved. + post( + "SECRET_TOKEN", + format!("{base}/update_value/{path}"), + value("$var:u/test-user-2/repo_url"), + ) + .await; + assert_eq!(approved_url(path).await, None); + 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. diff --git a/backend/windmill-api-integration-tests/tests/role_run_capability.rs b/backend/windmill-api-integration-tests/tests/role_run_capability.rs index dd1f206a55..42e8fb76ac 100644 --- a/backend/windmill-api-integration-tests/tests/role_run_capability.rs +++ b/backend/windmill-api-integration-tests/tests/role_run_capability.rs @@ -61,7 +61,14 @@ async fn test_withdrawn_run_refuses_runs(db: Pool) -> anyhow::Result<( set_overrides(r#"{"code": true}"#).await?; assert!(run("OPERATOR_TOKEN_1").await?.iter().all(|s| *s != 403)); - set_overrides(r#"{"code": true, "run": false}"#).await?; + // Through the route: the operator's login, cached above with `run` granted, must not keep it. + let resp = reqwest::Client::new() + .post(format!("{api}/workspaces/role_overrides")) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&serde_json::json!({"operator": {"capabilities": {"code": true, "run": false}}})) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); // 403, not 401, which the frontend reads as a dead session. assert_eq!(run("OPERATOR_TOKEN_1").await?, vec![403, 403, 403]); assert!(run("SECRET_TOKEN").await?.iter().all(|s| *s != 403)); diff --git a/backend/windmill-api-integration-tests/tests/users.rs b/backend/windmill-api-integration-tests/tests/users.rs index 1372847720..15f3a2d853 100644 --- a/backend/windmill-api-integration-tests/tests/users.rs +++ b/backend/windmill-api-integration-tests/tests/users.rs @@ -1282,6 +1282,352 @@ async fn test_rename_from_reserved_name_keeps_system_jobs( Ok(()) } +/// Schedules, triggers and folder default rules run as `permissioned_as`; one left on the old +/// username no longer resolves, and the server disables the schedule at its next push. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_rename_moves_run_as_of_schedules_and_triggers( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::raw_sql( + r#"INSERT INTO schedule (workspace_id, path, edited_by, edited_at, schedule, timezone, enabled, script_path, is_flow, email, permissioned_as, extra_perms) + VALUES ('test-workspace', 'f/ops/nightly', 'test-user-2', NOW(), '0 * * * *', 'UTC', true, 'f/ops/job', false, 'test2@windmill.dev', 'u/test-user-2', '{}'); + INSERT INTO http_trigger (workspace_id, path, route_path, route_path_key, script_path, is_flow, edited_by, permissioned_as, edited_at, extra_perms, http_method, authentication_method, mode) + VALUES ('test-workspace', 'u/test-user-2/hook', '/hook', 'hook', 'u/test-user-2/job', false, 'test-user-2', 'u/test-user-2', NOW(), '{"u/test-user-2": true}', 'post', 'none', 'enabled'); + INSERT INTO kafka_trigger (workspace_id, path, kafka_resource_path, topics, group_id, script_path, is_flow, edited_by, permissioned_as) + VALUES ('test-workspace', 'u/test-user-2/k', 'f/ops/kafka', '{t}', 'g', 'f/ops/job', false, 'test-user-2', 'u/test-user-2'); + INSERT INTO kafka_pending_commits (workspace_id, kafka_trigger_path, topic, partition, "offset") + VALUES ('test-workspace', 'u/test-user-2/k', 't', 0, 1); + INSERT INTO folder (workspace_id, name, display_name, owners, extra_perms, created_by, default_permissioned_as) + VALUES ('test-workspace', 'ops', 'ops', '{}', '{}', 'test-user', + '[{"path_glob": "a/*", "permissioned_as": "u/test-user"}, {"path_glob": "*", "permissioned_as": "u/test-user-2"}]');"#, + ) + .execute(&db) + .await?; + + let resp = authed(client().post(format!( + "http://localhost:{port}/api/users/rename/test2@windmill.dev" + ))) + .json(&json!({ "new_username": "alice" })) + .send() + .await?; + assert_eq!(resp.status(), 200, "rename: {}", resp.text().await?); + + let schedule: String = sqlx::query_scalar( + "SELECT permissioned_as FROM schedule WHERE workspace_id = 'test-workspace' AND path = 'f/ops/nightly'", + ) + .fetch_one(&db) + .await?; + assert_eq!(schedule, "u/alice"); + + let trigger: (String, String, String, String, serde_json::Value) = sqlx::query_as( + "SELECT path, script_path, edited_by, permissioned_as, extra_perms FROM http_trigger + WHERE workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + trigger, + ( + "u/alice/hook".into(), + "u/alice/job".into(), + "alice".into(), + "u/alice".into(), + json!({ "u/alice": true }) + ) + ); + + let pending_commit: String = + sqlx::query_scalar("SELECT kafka_trigger_path FROM kafka_pending_commits") + .fetch_one(&db) + .await?; + assert_eq!(pending_commit, "u/alice/k"); + + let rules: serde_json::Value = sqlx::query_scalar( + "SELECT default_permissioned_as FROM folder WHERE workspace_id = 'test-workspace' AND name = 'ops'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + rules, + json!([ + { "path_glob": "a/*", "permissioned_as": "u/test-user" }, + { "path_glob": "*", "permissioned_as": "u/alice" } + ]) + ); + + Ok(()) +} + +/// The rename moves the user's runnables, so every handler naming one must follow in the form its +/// column stores, or it fails exactly when it fires. A handler under another user's path stays. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_rename_moves_handler_paths(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::raw_sql( + r#"INSERT INTO schedule (workspace_id, path, edited_by, edited_at, schedule, timezone, enabled, script_path, is_flow, email, permissioned_as, extra_perms, on_failure, on_recovery, on_success, dynamic_skip) + VALUES ('test-workspace', 'f/ops/nightly', 'test-user', NOW(), '0 * * * *', 'UTC', true, 'f/ops/job', false, 'test@windmill.dev', 'u/test-user', '{}', + 'script/u/test-user-2/on_fail', 'flow/u/test-user-2/on_recover', 'script/u/test-user/on_success', 'u/test-user-2/skip'); + INSERT INTO http_trigger (workspace_id, path, route_path, route_path_key, script_path, is_flow, edited_by, permissioned_as, edited_at, extra_perms, http_method, authentication_method, mode, error_handler_path) + VALUES ('test-workspace', 'f/ops/hook', '/hook', 'hook', 'f/ops/job', false, 'test-user', 'u/test-user', NOW(), '{}', 'post', 'none', 'enabled', 'u/test-user-2/trigger_err'); + INSERT INTO kafka_trigger (workspace_id, path, kafka_resource_path, topics, group_id, script_path, is_flow, edited_by, permissioned_as, error_handler_path, server_id) + VALUES ('test-workspace', 'f/ops/k', 'f/ops/kafka', '{t}', 'g', 'f/ops/job', false, 'test-user', 'u/test-user', 'u/test-user/trigger_err', 'srv'), + ('test-workspace', 'f/ops/k2', 'f/ops/kafka', '{t}', 'g', 'f/ops/job', false, 'test-user', 'u/test-user', 'u/test-user-2/trigger_err', 'srv'); + UPDATE workspace_settings SET + error_handler = '{"path": "script/u/test-user-2/ws_err", "extra_args": {"channel": "ops"}, "muted_on_cancel": true}', + success_handler = '{"path": "flow/u/test-user-2/ws_ok"}', + variable_expiration_handler = '{"path": "script/u/test-user/expiry", "notify_before_secs": 60}', + slack_command_script = 'script/u/test-user-2/slack_cmd', + teams_command_script = 'u/test-user/teams_cmd', + default_app = 'u/test-user-2/home' + WHERE workspace_id = 'test-workspace';"#, + ) + .execute(&db) + .await?; + + let resp = authed(client().post(format!( + "http://localhost:{port}/api/users/rename/test2@windmill.dev" + ))) + .json(&json!({ "new_username": "alice" })) + .send() + .await?; + assert_eq!(resp.status(), 200, "rename: {}", resp.text().await?); + + let schedule: (String, String, String, String) = sqlx::query_as( + "SELECT on_failure, on_recovery, on_success, dynamic_skip FROM schedule + WHERE workspace_id = 'test-workspace' AND path = 'f/ops/nightly'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + schedule, + ( + "script/u/alice/on_fail".into(), + "flow/u/alice/on_recover".into(), + "script/u/test-user/on_success".into(), + "u/alice/skip".into() + ) + ); + + let http: String = sqlx::query_scalar( + "SELECT error_handler_path FROM http_trigger WHERE workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!(http, "u/alice/trigger_err"); + // A listener whose handler moved must restart to load it; one whose handler stayed is left be. + let kafka: Vec<(String, String, Option)> = sqlx::query_as( + "SELECT path, error_handler_path, server_id FROM kafka_trigger + WHERE workspace_id = 'test-workspace' ORDER BY path", + ) + .fetch_all(&db) + .await?; + assert_eq!( + kafka, + vec![ + ( + "f/ops/k".into(), + "u/test-user/trigger_err".into(), + Some("srv".into()) + ), + ("f/ops/k2".into(), "u/alice/trigger_err".into(), None), + ] + ); + + let settings: (serde_json::Value, serde_json::Value, serde_json::Value) = sqlx::query_as( + "SELECT error_handler, success_handler, variable_expiration_handler FROM workspace_settings + WHERE workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + settings, + ( + json!({ "path": "script/u/alice/ws_err", "extra_args": { "channel": "ops" }, "muted_on_cancel": true }), + json!({ "path": "flow/u/alice/ws_ok" }), + json!({ "path": "script/u/test-user/expiry", "notify_before_secs": 60 }) + ) + ); + + let commands: (String, String, String) = sqlx::query_as( + "SELECT slack_command_script, teams_command_script, default_app FROM workspace_settings + WHERE workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + commands, + ( + "script/u/alice/slack_cmd".into(), + "u/test-user/teams_cmd".into(), + "u/alice/home".into() + ) + ); + + Ok(()) +} + +/// Outside a superadmin's workspaces `u/{password.username}` resolves to them, so their rows there +/// follow the rename — but not in a workspace where a member holds that name, where it was theirs. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_rename_superadmin_moves_run_as_outside_their_workspaces( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::raw_sql( + r#"INSERT INTO workspace (id, name, owner) VALUES ('no-member', 'no-member', 'test-user'), ('like-named', 'like-named', 'test-user'); + INSERT INTO usr (workspace_id, email, username, is_admin, role) + VALUES ('like-named', 'test3@windmill.dev', 'test-user', false, 'User'); + INSERT INTO schedule (workspace_id, path, edited_by, edited_at, schedule, timezone, enabled, script_path, is_flow, email, permissioned_as, extra_perms) + VALUES ('no-member', 'f/ops/nightly', 'test-user', NOW(), '0 * * * *', 'UTC', true, 'f/ops/job', false, 'test@windmill.dev', 'u/test-user', '{}'), + ('like-named', 'f/ops/nightly', 'test-user', NOW(), '0 * * * *', 'UTC', true, 'f/ops/job', false, 'test3@windmill.dev', 'u/test-user', '{}');"#, + ) + .execute(&db) + .await?; + + let resp = authed(client().post(format!( + "http://localhost:{port}/api/users/rename/test@windmill.dev" + ))) + .json(&json!({ "new_username": "root" })) + .send() + .await?; + assert_eq!(resp.status(), 200, "rename: {}", resp.text().await?); + + let schedules: Vec<(String, String)> = sqlx::query_as( + "SELECT workspace_id, permissioned_as FROM schedule WHERE path = 'f/ops/nightly' ORDER BY workspace_id", + ) + .fetch_all(&db) + .await?; + assert_eq!( + schedules, + vec![ + ("like-named".into(), "u/test-user".into()), + ("no-member".into(), "u/root".into()), + ] + ); + + Ok(()) +} + +/// A legacy `group-ops` member canonicalizes to `g/ops`; renaming them must not hand the group's +/// schedules and folder rules to the member. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_rename_group_prefixed_member_keeps_group_run_as( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::raw_sql( + r#"UPDATE usr SET username = 'group-ops' WHERE email = 'test2@windmill.dev'; + UPDATE password SET username = 'group-ops' WHERE email = 'test2@windmill.dev'; + INSERT INTO schedule (workspace_id, path, edited_by, edited_at, schedule, timezone, enabled, script_path, is_flow, email, permissioned_as, extra_perms) + VALUES ('test-workspace', 'f/ops/nightly', 'test-user', NOW(), '0 * * * *', 'UTC', true, 'f/ops/job', false, 'test@windmill.dev', 'g/ops', '{}'); + INSERT INTO folder (workspace_id, name, display_name, owners, extra_perms, created_by, default_permissioned_as) + VALUES ('test-workspace', 'ops', 'ops', '{}', '{}', 'test-user', '[{"path_glob": "*", "permissioned_as": "g/ops"}]');"#, + ) + .execute(&db) + .await?; + + let resp = authed(client().post(format!( + "http://localhost:{port}/api/users/rename/test2@windmill.dev" + ))) + .json(&json!({ "new_username": "alice" })) + .send() + .await?; + assert_eq!(resp.status(), 200, "rename: {}", resp.text().await?); + + let (schedule, rules): (String, serde_json::Value) = sqlx::query_as( + "SELECT s.permissioned_as, f.default_permissioned_as FROM schedule s, folder f + WHERE s.path = 'f/ops/nightly' AND f.name = 'ops'", + ) + .fetch_one(&db) + .await?; + assert_eq!(schedule, "g/ops"); + assert_eq!( + rules, + json!([{ "path_glob": "*", "permissioned_as": "g/ops" }]) + ); + + Ok(()) +} + +/// Same rule for the runnables that carry their principal themselves: scripts, flows, drafts, +/// apps and agents running as `g/ops` stay the group's. The agent sits in a workspace the +/// member is not in, which is what the instance-wide sweep reaches. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_rename_group_prefixed_member_keeps_group_runnables( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::raw_sql( + r#"UPDATE usr SET username = 'group-ops' WHERE email = 'test2@windmill.dev'; + UPDATE password SET username = 'group-ops' WHERE email = 'test2@windmill.dev'; + INSERT INTO workspace (id, name, owner) VALUES ('other-workspace', 'other-workspace', 'test-user'); + INSERT INTO script (workspace_id, path, hash, content, summary, description, language, created_by, created_at, on_behalf_of, on_behalf_of_email) + VALUES ('test-workspace', 'f/ops/job', 96001, 'def main(): pass', '', '', 'python3', 'test-user', NOW(), 'g/ops', 'group-ops@windmill.dev'); + INSERT INTO flow (workspace_id, path, summary, description, value, edited_by, edited_at, schema, extra_perms, on_behalf_of, on_behalf_of_email) + VALUES ('test-workspace', 'f/ops/flow', '', '', '{"modules": []}', 'test-user', NOW(), '{}', '{}', 'g/ops', 'group-ops@windmill.dev'); + INSERT INTO draft (workspace_id, path, typ, value, email) + VALUES ('test-workspace', 'f/ops/job', 'script', '{"on_behalf_of": "g/ops", "on_behalf_of_email": "group-ops@windmill.dev"}', 'test@windmill.dev'), + ('test-workspace', 'f/ops/app', 'app', '{"policy": {"on_behalf_of": "g/ops", "on_behalf_of_email": "test2@windmill.dev"}}', 'test@windmill.dev'); + INSERT INTO app (workspace_id, path, summary, policy, versions) + VALUES ('test-workspace', 'f/ops/app', '', '{"on_behalf_of": "g/ops", "on_behalf_of_email": "test2@windmill.dev"}', '{}'); + INSERT INTO resource (workspace_id, path, value, resource_type, created_by) + VALUES ('other-workspace', 'f/ops/agent', '{"run_on_behalf_of": true, "on_behalf_of": "g/ops"}', 'ai_agent', 'test-user');"#, + ) + .execute(&db) + .await?; + + let resp = authed(client().post(format!( + "http://localhost:{port}/api/users/rename/test2@windmill.dev" + ))) + .json(&json!({ "new_username": "alice" })) + .send() + .await?; + assert_eq!(resp.status(), 200, "rename: {}", resp.text().await?); + + let principals: Vec<(String, Option)> = sqlx::query_as( + "SELECT 'script', on_behalf_of FROM script WHERE path = 'f/ops/job' + UNION ALL SELECT 'flow', on_behalf_of FROM flow WHERE path = 'f/ops/flow' + UNION ALL SELECT 'draft ' || typ, COALESCE(value->>'on_behalf_of', value->'policy'->>'on_behalf_of') + FROM draft WHERE path LIKE 'f/ops/%' + UNION ALL SELECT 'app', policy->>'on_behalf_of' FROM app WHERE path = 'f/ops/app' + UNION ALL SELECT 'agent', value->>'on_behalf_of' FROM resource WHERE path = 'f/ops/agent' + ORDER BY 1", + ) + .fetch_all(&db) + .await?; + assert_eq!( + principals, + [ + "agent", + "app", + "draft app", + "draft script", + "flow", + "script" + ] + .map(|k| (k.to_string(), Some("g/ops".to_string()))) + .to_vec() + ); + + Ok(()) +} + #[sqlx::test(migrations = "../migrations", fixtures("base"))] async fn test_generated_username_skips_anonymous(db: Pool) -> anyhow::Result<()> { let mut tx = db.begin().await?; diff --git a/backend/windmill-api-integration-tests/tests/workspaces.rs b/backend/windmill-api-integration-tests/tests/workspaces.rs index c6ec1d5c6c..e3640aa1bb 100644 --- a/backend/windmill-api-integration-tests/tests/workspaces.rs +++ b/backend/windmill-api-integration-tests/tests/workspaces.rs @@ -1324,3 +1324,41 @@ async fn test_create_workspace_validates_chosen_username(db: Pool) -> Ok(()) } + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn archiving_a_workspace_makes_its_public_apps_private( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::query( + "INSERT INTO app (workspace_id, path, summary, policy, versions) VALUES + ('test-workspace', 'u/test-user/public', '', '{\"execution_mode\": \"anonymous\"}', '{}'), + ('test-workspace', 'u/test-user/members', '', '{\"execution_mode\": \"publisher\"}', '{}')", + ) + .execute(&db) + .await?; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let resp = authed(client().post(format!( + "http://localhost:{port}/api/w/test-workspace/workspaces/archive" + ))) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let modes: Vec<(String, String)> = sqlx::query_as( + "SELECT path, policy->>'execution_mode' FROM app + WHERE workspace_id = 'test-workspace' ORDER BY path", + ) + .fetch_all(&db) + .await?; + assert_eq!( + modes, + [ + ("u/test-user/members".to_string(), "publisher".to_string()), + ("u/test-user/public".to_string(), "publisher".to_string()), + ] + ); + Ok(()) +} diff --git a/backend/windmill-api-jobs/src/execution.rs b/backend/windmill-api-jobs/src/execution.rs index 445e0ea84a..e16d8b4c61 100644 --- a/backend/windmill-api-jobs/src/execution.rs +++ b/backend/windmill-api-jobs/src/execution.rs @@ -37,7 +37,7 @@ use windmill_common::{ get_latest_flow_version_info_for_path, jobs::{ check_tag_available_for_workspace_internal, format_result, script_path_to_payload, - JobPayload, + ChosenBy, JobPayload, }, runnable_ref::RunnableRef, triggers::TriggerMetadata, @@ -577,7 +577,7 @@ pub async fn run_wait_result_internal( SELECT result AS \"result: sqlx::types::Json>\", result_columns, - status = 'success' AS \"success!\" + status IN ('success', 'skipped') AS \"success!\" FROM v2_job_completed WHERE @@ -623,8 +623,146 @@ pub async fn run_wait_result_internal( } } -pub fn result_to_response(result: Box, success: bool) -> error::Result { +/// Content types a workspace without a paid plan may serve on Windmill Cloud: data, never a +/// document a browser renders as a page (HTML, SVG, XML, PDF, JS, ...). +const PLAIN_CONTENT_TYPES: [&str; 9] = [ + "application/json", + "application/x-ndjson", + "text/plain", + "text/csv", + "text/calendar", + "image/png", + "image/jpeg", + "image/gif", + "image/webp", +]; + +/// `windmill_headers` a workspace without a paid plan may not set on Windmill Cloud. Each turns +/// our domain into something other than a data API: a redirect, a file download, a native login +/// prompt, or a cookie or cleared site data on it. `Content-Type` is checked by value instead: +/// set there it overrides the JSON body's own. +const PAID_ONLY_HEADERS: [&str; 6] = [ + "location", + "refresh", + "content-disposition", + "www-authenticate", + "set-cookie", + "clear-site-data", +]; + +fn content_type_allowed(ct: &str) -> bool { + // A browser reads a comma-separated Content-Type as a list and uses its last valid type, + // so `text/plain, text/html` renders as HTML. + if ct.contains(',') { + return false; + } + let media_type = ct.split(';').next().unwrap_or("").trim(); + PLAIN_CONTENT_TYPES + .iter() + .any(|t| t.eq_ignore_ascii_case(media_type)) +} + +fn content_type_hint(ct: &str) -> String { + let ct = ct.to_ascii_lowercase(); + if ct.contains(',') { + "Set a single content type.".to_string() + } else if ct.contains("svg") { + "Render the image as image/png instead.".to_string() + } else { + format!( + "Allowed content types are {}.", + PLAIN_CONTENT_TYPES.join(", ") + ) + } +} + +/// Why serving this composite result would make our domain serve a web page, a redirect or one +/// of [`PAID_ONLY_HEADERS`], which a free cloud workspace may not do, with how to fix it. +/// `None` when it serves data only. +fn paid_plan_refusal( + status_code: Option, + content_type: Option<&str>, + headers: Option<&HashMap>, +) -> Option { + if let Some(c) = status_code.filter(|c| (300..400).contains(c)) { + return Some(format!( + "windmill_status_code {c} is a redirect. Return the URL in the result instead." + )); + } + if let Some(ct) = content_type.filter(|ct| !content_type_allowed(ct)) { + return Some(format!( + "windmill_content_type \"{ct}\" is not allowed. {}", + content_type_hint(ct) + )); + } + for (k, v) in headers.into_iter().flatten() { + let name = k.trim(); + if name.eq_ignore_ascii_case("content-type") { + if !content_type_allowed(v) { + return Some(format!( + "windmill_headers \"{k}: {v}\" is not allowed. {}", + content_type_hint(v) + )); + } + } else if PAID_ONLY_HEADERS + .iter() + .any(|n| n.eq_ignore_ascii_case(name)) + { + let hint = if ["location", "refresh"] + .iter() + .any(|n| n.eq_ignore_ascii_case(name)) + { + " Return the URL in the result instead." + } else { + "" + }; + return Some(format!("windmill_headers \"{k}\" is not allowed.{hint}")); + } + } + None +} + +/// [`result_to_response`] for a response served over HTTP, with the workspace's plan applied. +/// The plan is looked up only for a result that needs it, so a plan lookup failure never +/// holds up an ordinary response. Callers must already have authorized the request for `w_id` +/// and the job that produced `result`. +pub async fn result_to_http_response( + db: &DB, + w_id: &str, + result: Box, + success: bool, +) -> error::Result { let composite_result = parse_result_object::(result.get()); + let needs_plan = composite_result.as_ref().is_some_and(|c| { + paid_plan_refusal( + c.windmill_status_code, + c.windmill_content_type.as_deref(), + c.windmill_headers.as_ref(), + ) + .is_some() + }); + let rich_responses_allowed = + !needs_plan || windmill_common::workspaces::paid_features_allowed(db, w_id).await?; + composite_to_response(composite_result, result, success, rich_responses_allowed) +} + +/// Shapes a job result into a response. `rich_responses_allowed: false` refuses a result that +/// [`paid_plan_refusal`] refuses; HTTP callers get it from [`result_to_http_response`]. +pub fn result_to_response( + result: Box, + success: bool, + rich_responses_allowed: bool, +) -> error::Result { + let composite_result = parse_result_object::(result.get()); + composite_to_response(composite_result, result, success, rich_responses_allowed) +} + +fn composite_to_response( + composite_result: Option, + result: Box, + success: bool, + rich_responses_allowed: bool, +) -> error::Result { match composite_result { Some(WindmillCompositeResult { windmill_status_code, @@ -633,6 +771,19 @@ pub fn result_to_response(result: Box, success: bool) -> error::Result windmill_content_transfer_encoding, result: result_value, }) => { + if !rich_responses_allowed { + if let Some(reason) = paid_plan_refusal( + windmill_status_code, + windmill_content_type.as_deref(), + windmill_headers.as_ref(), + ) { + return Err(Error::BadRequest(format!( + "The job ran, but its response was refused: {reason} Web pages, \ + redirects and some response headers require a paid plan on Windmill \ + Cloud: upgrade this workspace in Workspace Settings > Premium plans." + ))); + } + } if windmill_content_type.is_none() && windmill_status_code.is_none() && windmill_headers.is_none() @@ -802,7 +953,7 @@ pub async fn run_wait_result( ) .await?; - result_to_response(result, success) + result_to_http_response(db, w_id, result, success).await } // --------------------------------------------------------------------------- @@ -878,11 +1029,31 @@ pub async fn check_queue_too_long(db: &DB, queue_limit: Option) -> error::R // Flow run helpers // --------------------------------------------------------------------------- +/// Record the run's memory id, and make the run the one turn that holds it: a run started with a +/// memory id a still-queued run holds is refused with a 409, so two turns never write the same +/// memory over each other. A holder whose agent parked hands the turn over instead. For a chat flow, call it after `handle_chat_conversation_messages`, +/// whose refusal names the running turn the way the chat follows it. pub async fn set_flow_memory_id( tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + w_id: &str, job_id: Uuid, memory_id: Uuid, ) -> error::Result<()> { + if let Some(refused) = claim_memory_turn(tx, w_id, memory_id, job_id).await? { + let error = if refused.parked { + "another run with this memory_id is waiting, but has steps after its AI agent, so it \ + cannot hand its conversation over. Wait for it, or pass `take_over=true` to stop it \ + and run this one instead." + } else { + "another run with this memory_id is still running. Wait for it, or pass \ + `take_over=true` to stop it and run this one instead." + }; + return Err(Error::Generic( + StatusCode::CONFLICT, + serde_json::json!({ "error": error, "running_turn": { "job_id": refused.holder } }) + .to_string(), + )); + } sqlx::query!( "UPDATE v2_job_status SET flow_status = jsonb_set( @@ -899,6 +1070,248 @@ pub async fn set_flow_memory_id( Ok(()) } +/// A claim refused: the queued run that holds the memory id, and whether its agent is parked +/// where the run cannot hand its conversation over. +struct RefusedClaim { + holder: Uuid, + parked: bool, +} + +/// Make `job_id` the holder of the memory id, or return the queued run that holds it and cannot +/// hand it over. +/// +/// Lock, then look, in separate statements: under read committed, a statement that waited on a +/// row lock still evaluates its subqueries with the snapshot it started with, so a single upsert +/// checking the queue would miss the holder that committed while it waited. +async fn claim_memory_turn( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + w_id: &str, + memory_id: Uuid, + job_id: Uuid, +) -> error::Result> { + // A claim the monitor deletes while this waits on it is gone, not held: insert again. + for _ in 0..3 { + let inserted = sqlx::query_scalar!( + "INSERT INTO ai_memory_turn (workspace_id, memory_id, job_id) VALUES ($1, $2, $3) + ON CONFLICT (workspace_id, memory_id) DO NOTHING RETURNING job_id", + w_id, + memory_id, + job_id + ) + .fetch_optional(&mut **tx) + .await?; + if inserted.is_some() { + return Ok(None); + } + let claim = sqlx::query!( + "SELECT job_id, handed_jobs FROM ai_memory_turn + WHERE workspace_id = $1 AND memory_id = $2 FOR UPDATE", + w_id, + memory_id + ) + .fetch_optional(&mut **tx) + .await?; + let Some((holder, unadopted)) = claim.map(|c| (c.job_id, c.handed_jobs)) else { + continue; + }; + let queued = sqlx::query_scalar!( + r#"SELECT EXISTS (SELECT 1 FROM v2_job_queue WHERE id = $1) AS "queued!""#, + holder + ) + .fetch_one(&mut **tx) + .await?; + let handed_jobs = if queued { + match hand_over_parked_turn(tx, holder).await? { + Some(jobs) => Some(jobs), + None => { + let parked = sqlx::query_scalar!( + r#"SELECT EXISTS (SELECT 1 FROM ai_agent_checkpoint c + JOIN v2_job_queue q ON q.id = c.job_id JOIN v2_job j ON j.id = c.job_id + WHERE (j.parent_job = $1 OR j.root_job = $1) + AND q.suspend > 0 AND q.suspend_until IS NOT NULL) AS "parked!""#, + holder + ) + .fetch_one(&mut **tx) + .await?; + return Ok(Some(RefusedClaim { holder, parked })); + } + } + } else { + // Jobs handed to the ended run and never adopted: cancelled, as the monitor does + // for a claim it deletes, rather than dropped with the row. + if let Some(unadopted) = &unadopted { + windmill_common::flow_conversations::cancel_unadopted_handed_jobs( + &mut **tx, unadopted, + ) + .await?; + } + None + }; + sqlx::query!( + "UPDATE ai_memory_turn SET job_id = $3, handed_jobs = $4 + WHERE workspace_id = $1 AND memory_id = $2", + w_id, + memory_id, + job_id, + handed_jobs + ) + .execute(&mut **tx) + .await?; + return Ok(None); + } + Err(Error::internal_err(format!( + "Could not claim memory id {memory_id}: its claim kept being released" + ))) +} + +/// A run whose agent parked has given its answer or waits on a person, so a new turn continues +/// the conversation rather than being refused. The parked agent is woken to end with what it has, +/// any open approval or question dropped, and its background jobs are returned by flow step id +/// for the new run's agent to adopt. `None` when there is no such agent. +/// +/// Only an agent that is the run's last top-level step, where the run is at: after it the run +/// ends, so nothing of it can write the memory or the chat beside the new turn. A step after it, +/// or one in a parallel branch, would. `refuse_running_turn` holds the same condition. +/// +/// Zeroing `suspend` under the row lock is what keeps the monitor's wake and an answer from +/// resuming the old turn as well: both only act on a row still parked. +async fn hand_over_parked_turn( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + holder: Uuid, +) -> error::Result> { + let parked = sqlx::query!( + r#"UPDATE v2_job_queue q SET suspend = 0 + FROM ai_agent_checkpoint c, v2_job j, v2_job_status s + WHERE c.job_id = q.id AND j.id = q.id AND j.parent_job = $1 AND s.id = $1 + AND (s.flow_status->>'step')::int = jsonb_array_length(s.flow_status->'modules') - 1 + AND s.flow_status->'modules'->-1->>'job' = q.id::text + AND q.suspend > 0 AND q.suspend_until IS NOT NULL + RETURNING q.id, j.flow_step_id, c.checkpoint->'background' AS "background""#, + holder + ) + .fetch_all(&mut **tx) + .await?; + if parked.is_empty() { + return Ok(None); + } + let ids: Vec = parked.iter().map(|p| p.id).collect(); + sqlx::query!( + "UPDATE ai_agent_checkpoint + SET checkpoint = jsonb_set(checkpoint, '{handed_over}', 'true'), waiting_on = '{}' + WHERE job_id = ANY($1)", + &ids + ) + .execute(&mut **tx) + .await?; + let jobs = parked + .into_iter() + .filter_map(|p| Some((p.flow_step_id?, p.background?))) + .collect::>(); + Ok(Some(serde_json::Value::Object(jobs))) +} + +/// How long `take_over_memory_turn` waits for the stopped run to leave the queue: an agent step's +/// cancel grace period, plus the time its worker takes to notice the cancel. +const TAKE_OVER_WAIT: std::time::Duration = std::time::Duration::from_secs(40); + +/// With `take_over`, stop the run that holds the memory id so this one can claim it: cancel it, +/// then wait for it to leave the queue, which its agents spend saving what they have to memory. +/// Only who started that run, or an admin, can stop it, and a restricted token only with an +/// unconfined `jobs:cancel` grant: the memory id is not confined to the flow being run. +pub async fn take_over_memory_turn( + db: &DB, + authed: &ApiAuthed, + w_id: &str, + flow_path: &str, + run_query: &RunJobQuery, +) -> error::Result<()> { + if !run_query.take_over.unwrap_or(false) { + return Ok(()); + } + let Some(memory_id) = run_query.memory_key(w_id, flow_path) else { + return Err(Error::BadRequest("take_over needs a memory_id".to_string())); + }; + let scopes = authed.scopes.as_deref(); + if scopes.is_some() + && !(windmill_api_auth::scopes::has_job_cancel_grant(scopes) + && windmill_api_auth::scopes::job_cancel_path_confinement(scopes).is_none()) + { + return Err(Error::NotAuthorized( + "take_over needs a token that can cancel any job (`jobs:cancel`)".to_string(), + )); + } + let holder = sqlx::query!( + "SELECT t.job_id, j.created_by, j.tag FROM ai_memory_turn t + JOIN v2_job_queue q ON q.id = t.job_id + JOIN v2_job j ON j.id = t.job_id + WHERE t.workspace_id = $1 AND t.memory_id = $2", + w_id, + memory_id + ) + .fetch_optional(db) + .await?; + let Some((job_id, created_by, tag)) = holder.map(|h| (h.job_id, h.created_by, h.tag)) else { + return Ok(()); + }; + // A token confined to tags reads, and so cancels, only jobs on them. + if get_scope_tags(authed).is_some_and(|tags| !tags.contains(&tag.as_str())) { + return Err(Error::NotAuthorized(format!( + "the running turn is on tag {tag}, which this token cannot reach" + ))); + } + if created_by != authed.username && !authed.is_admin { + return Err(Error::NotAuthorized( + "only who started the running turn, or an admin, can take it over".to_string(), + )); + } + let (tx, _) = windmill_queue::cancel_job( + &authed.username, + Some("taken over by a new run".to_string()), + job_id, + w_id, + db.begin().await?, + db, + false, + false, + ) + .await?; + tx.commit().await?; + windmill_audit::audit_oss::audit_log( + db, + authed, + "jobs.cancel", + ActionKind::Delete, + w_id, + Some(&job_id.to_string()), + None, + ) + .await?; + + let deadline = std::time::Instant::now() + TAKE_OVER_WAIT; + loop { + let queued = sqlx::query_scalar!( + r#"SELECT EXISTS (SELECT 1 FROM v2_job_queue WHERE id = $1) AS "queued!""#, + job_id + ) + .fetch_one(db) + .await?; + if !queued { + return Ok(()); + } + if std::time::Instant::now() > deadline { + return Err(Error::Generic( + StatusCode::CONFLICT, + serde_json::json!({ + "error": "the running turn was cancelled but has not stopped yet; retry shortly", + "running_turn": { "job_id": job_id }, + }) + .to_string(), + )); + } + tokio::time::sleep(std::time::Duration::from_millis(250)).await; + } +} + pub async fn handle_chat_conversation_messages( tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, authed: &ApiAuthed, @@ -1014,6 +1427,7 @@ pub async fn run_flow<'c>( )> { let mut run_query = run_query; drop_unclaimable_run_lineage(db, w_id, &mut run_query, authed).await?; + take_over_memory_turn(db, authed, w_id, flow_path, &run_query).await?; let on_behalf_of = flow_version_info.on_behalf_of(w_id, &db).await?; let FlowVersionInfo { version, @@ -1117,11 +1531,6 @@ pub async fn run_flow<'c>( ) .await?; - // Set memory_id if provided (for agent memory) - if let Some(memory_id) = run_query.memory_key(w_id, flow_path) { - set_flow_memory_id(&mut tx, uuid, memory_id).await?; - } - // Handle conversation messages for chat-enabled flows if chat_input_enabled.unwrap_or(false) { handle_chat_conversation_messages( @@ -1138,6 +1547,11 @@ pub async fn run_flow<'c>( .await?; } + // Set memory_id if provided (for agent memory) + if let Some(memory_id) = run_query.memory_key(w_id, flow_path) { + set_flow_memory_id(&mut tx, w_id, uuid, memory_id).await?; + } + // If we were given a transaction, return it; otherwise commit it if return_tx { Ok(( @@ -1167,7 +1581,7 @@ pub async fn run_flow_and_wait_result( run_query: RunJobQuery, args: PushArgsOwned, trigger: Option, -) -> error::Result { +) -> error::Result<(Box, bool)> { let (uuid, early_return, has_failure_module, _) = run_flow( authed, db, @@ -1182,7 +1596,7 @@ pub async fn run_flow_and_wait_result( ) .await?; - run_wait_result( + run_wait_result_internal( &db, uuid, w_id, @@ -1242,6 +1656,7 @@ pub async fn push_flow_job_by_path_into_queue<'c>( pub async fn push_script_job_by_path_into_queue<'c>( authed: ApiAuthed, + chosen_by: ChosenBy, db: DB, tx_o: Option>, user_db: UserDB, @@ -1267,6 +1682,7 @@ pub async fn push_script_job_by_path_into_queue<'c>( let (job_payload, tag, delete_after_use, delete_after_secs, timeout, on_behalf_of) = script_path_to_payload( script, + chosen_by.origin(authed.to_authed_ref()), Some(userdb_authed), db.clone(), &w_id, @@ -1381,6 +1797,7 @@ mod result_to_response_tests { r#"{{"wm_content_type":"application/pdf","wm_content_transfer_encoding":"base64","result":"{b64}"}}"# )), true, + true, ) .expect("response"); @@ -1399,6 +1816,7 @@ mod result_to_response_tests { r#"{"wm_content_type":"application/pdf","wm_content_transfer_encoding":"base64","result":"not valid base64!!"}"#, ), true, + true, ); assert!(res.is_err(), "invalid base64 must not silently fall back"); } @@ -1413,6 +1831,7 @@ mod result_to_response_tests { r#"{{"wm_content_type":"application/octet-stream","wm_content_transfer_encoding":"base64","result":{result}}}"# )), true, + true, ); assert!( res.is_err(), @@ -1428,6 +1847,7 @@ mod result_to_response_tests { r#"{"wm_content_type":"text/plain","wm_content_transfer_encoding":"gzip","result":"x"}"#, ), true, + true, ); assert!(res.is_err()); } @@ -1437,6 +1857,7 @@ mod result_to_response_tests { let res = result_to_response( raw(r#"{"wm_content_transfer_encoding":"base64","result":"aGk="}"#), true, + true, ); assert!(res.is_err()); } @@ -1448,6 +1869,7 @@ mod result_to_response_tests { let resp = result_to_response( raw(r#"{"wm_content_type":"text/html","result":"

hi

"}"#), true, + true, ) .expect("response"); @@ -1483,6 +1905,7 @@ mod result_to_response_tests { r#"{"wm_headers":{"content-type":"text/html","content-security-policy":"default-src *","x-content-type-options":"none"},"result":"

hi

"}"#, ), true, + true, ) .expect("response"); @@ -1503,6 +1926,7 @@ mod result_to_response_tests { r#"{{"wm_content_type":"text/html","wm_headers":{{"{name}":"content-security-policy, x-content-type-options"}},"result":"

hi

"}}"# )), true, + true, ); assert!(res.is_err(), "hop-by-hop header must be rejected: {name}"); } @@ -1511,9 +1935,69 @@ mod result_to_response_tests { #[tokio::test] async fn array_result_is_not_a_composite_response() { let json = r#"[201,"text/html",null,null,"

hi

"]"#; - let resp = result_to_response(raw(json), true).expect("response"); + let resp = result_to_response(raw(json), true, true).expect("response"); assert_eq!(resp.status(), StatusCode::OK); assert_eq!(body_bytes(resp).await, json.as_bytes()); } + + #[tokio::test] + async fn pages_and_redirects_need_a_paid_plan() { + let refused = [ + r#"{"wm_content_type":"text/html","result":"

hi

"}"#, + r#"{"wm_content_type":"TEXT/HTML; charset=utf-8","result":"

hi

"}"#, + r#"{"wm_content_type":"image/svg+xml","result":""}"#, + r#"{"wm_content_type":"application/pdf","result":"x"}"#, + r#"{"wm_status_code":302,"result":null}"#, + r#"{"wm_status_code":308,"result":null}"#, + r#"{"wm_headers":{"Location":"https://example.com"},"result":null}"#, + r#"{"wm_headers":{"refresh":"0;url=https://example.com"},"result":null}"#, + r#"{"wm_headers":{"Content-Type":"text/html"},"result":"

hi

"}"#, + r#"{"wm_content_type":"text/plain","wm_headers":{"Content-Disposition":"attachment; filename=\"x.exe\""},"result":"x"}"#, + r#"{"wm_status_code":401,"wm_headers":{"WWW-Authenticate":"Basic realm=\"login\""}}"#, + r#"{"wm_content_type":"text/plain; charset=utf-8, text/html","result":"

hi

"}"#, + r#"{"wm_headers":{"set-cookie":"token=x; Path=/"},"result":{"a":1}}"#, + r#"{"wm_headers":{"content-type":"image/svg+xml"},"result":""}"#, + r#"{"wm_headers":{"Clear-Site-Data":"\"cookies\""},"result":{"a":1}}"#, + ]; + for json in refused { + let res = result_to_response(raw(json), true, false); + assert!( + matches!(res, Err(Error::BadRequest(_))), + "must be refused: {json}" + ); + assert!( + result_to_response(raw(json), true, true).is_ok(), + "paid: {json}" + ); + } + + let allowed = [ + r#"{"a":1}"#, + r#"{"wm_content_type":"application/json","result":{"a":1}}"#, + r#"{"wm_content_type":"text/plain; charset=utf-8","result":"hi"}"#, + r#"{"wm_content_type":"image/png","wm_content_transfer_encoding":"base64","result":"aGk="}"#, + r#"{"wm_status_code":201,"wm_headers":{"x-custom":"1"},"result":{"a":1}}"#, + r#"{"wm_status_code":400,"result":"bad"}"#, + r#"{"wm_headers":{"content-type":"image/gif"},"result":"R0lGODlh"}"#, + ]; + for json in allowed { + assert!( + result_to_response(raw(json), true, false).is_ok(), + "must be allowed: {json}" + ); + } + + let Err(Error::BadRequest(msg)) = result_to_response( + raw(r#"{"wm_headers":{"content-type":"image/svg+xml"},"result":""}"#), + true, + false, + ) else { + panic!("svg must be refused"); + }; + assert!( + msg.contains("\"content-type: image/svg+xml\"") && msg.contains("image/png"), + "error must name the refused key and value and suggest a fix: {msg}" + ); + } } diff --git a/backend/windmill-api-jobs/src/types.rs b/backend/windmill-api-jobs/src/types.rs index 60bf802a4a..752a0fb81b 100644 --- a/backend/windmill-api-jobs/src/types.rs +++ b/backend/windmill-api-jobs/src/types.rs @@ -49,6 +49,8 @@ pub struct RunJobQuery { pub poll_delay_ms: Option, /// Any string; see [`RunJobQuery::memory_key`]. pub memory_id: Option, + /// Stop the run that holds `memory_id` and run this one instead of being refused. + pub take_over: Option, pub trigger_external_id: Option, pub service_name: Option, pub suspended_mode: Option, diff --git a/backend/windmill-api-schedule/src/lib.rs b/backend/windmill-api-schedule/src/lib.rs index eb952f157b..aff47aee8c 100644 --- a/backend/windmill-api-schedule/src/lib.rs +++ b/backend/windmill-api-schedule/src/lib.rs @@ -17,7 +17,8 @@ use sql_builder::{prelude::Bind, SqlBuilder}; use sqlx::{Postgres, Transaction}; use std::str::FromStr; use windmill_api_auth::{ - build_scope_path_predicate, check_scopes, maybe_refresh_folders, require_super_admin, ApiAuthed, + build_scope_path_predicate, check_scopes, composed::check_new_hub_paths, maybe_refresh_folders, + require_super_admin, ApiAuthed, }; use windmill_audit::audit_oss::audit_log; use windmill_audit::ActionKind; @@ -235,6 +236,15 @@ fn reject_reserved_schedule_path(path: &str) -> Result<()> { Ok(()) } +/// A retry the runs cannot parse would otherwise be saved and then fail every tick. +fn validate_retry(retry: &Option) -> Result<()> { + if let Some(retry) = retry { + serde_json::from_value::(retry.clone()) + .map_err(|e| Error::BadRequest(format!("Invalid retry: {e}")))?; + } + Ok(()) +} + /// Validate that a dynamic skip handler (script or flow) exists async fn validate_dynamic_skip<'c>( tx: &mut Transaction<'c, Postgres>, @@ -264,6 +274,15 @@ async fn validate_dynamic_skip<'c>( } } +/// A handler that does not parse is left out: it never runs, as a fire parses it the same way. +fn handler_runnables(handlers: [Option<&str>; 3]) -> Vec { + handlers + .into_iter() + .flatten() + .filter_map(|h| RunnableRef::from_prefixed(h).ok()) + .collect() +} + async fn create_schedule( authed: ApiAuthed, Extension(db): Extension, @@ -275,10 +294,11 @@ async fn create_schedule( reject_reserved_schedule_path(&ns.path)?; // Stored as parsed: the next-run check, the monitor's re-arm, the run history and renames // all match the stored target exactly against job paths, which never start with `/`. - if !ns.script_path.is_empty() { - ns.script_path = RunnableRef::from_path(&ns.script_path, ns.is_flow)? - .path() - .to_string(); + let target = (!ns.script_path.is_empty()) + .then(|| RunnableRef::from_path(&ns.script_path, ns.is_flow)) + .transpose()?; + if let Some(target) = &target { + ns.script_path = target.path().to_string(); } let authed = maybe_refresh_folders(&ns.path, &w_id, authed, &db).await; @@ -354,11 +374,21 @@ async fn create_schedule( Some(&resolved_email), )?; + let mut new_runnables = handler_runnables([ + ns.on_failure.as_deref(), + ns.on_recovery.as_deref(), + ns.on_success.as_deref(), + ]); + new_runnables.extend(target); + check_new_hub_paths(&new_runnables, &[], &authed, &db, &w_id).await?; + let mut tx: Transaction<'_, Postgres> = user_db.begin(&authed).await?; check_path_conflict(&mut tx, &w_id, &ns.path).await?; check_flow_conflict(&mut tx, &w_id, &ns.path, ns.is_flow, &ns.script_path).await?; + validate_retry(&ns.retry)?; + // Validate dynamic_skip if provided if let Some(handler_path) = &ns.dynamic_skip { validate_dynamic_skip(&mut tx, &w_id, handler_path).await?; @@ -590,14 +620,32 @@ async fn edit_schedule( Some(&resolved_email), )?; + let new_handlers = handler_runnables([ + es.on_failure.as_deref(), + es.on_recovery.as_deref(), + es.on_success.as_deref(), + ]); let mut tx = user_db.begin(&authed).await?; + validate_retry(&es.retry)?; + // Validate dynamic_skip if provided if let Some(handler_path) = &es.dynamic_skip { validate_dynamic_skip(&mut tx, &w_id, handler_path).await?; } let before = trigger_history::snapshot_row(&mut *tx, "schedule", &w_id, path).await?; + check_new_hub_paths( + &new_handlers, + &handler_runnables( + ["on_failure", "on_recovery", "on_success"] + .map(|f| before.as_ref().and_then(|b| b.get(f)?.as_str())), + ), + &authed, + &db, + &w_id, + ) + .await?; let schedule = sqlx::query_as!( Schedule, diff --git a/backend/windmill-api-scripts/src/asset_inference.rs b/backend/windmill-api-scripts/src/asset_inference.rs index 602228550d..82ecdf49b3 100644 --- a/backend/windmill-api-scripts/src/asset_inference.rs +++ b/backend/windmill-api-scripts/src/asset_inference.rs @@ -87,7 +87,7 @@ fn comment_prefix(lang: &ScriptLang) -> Option<&'static str> { /// Mirror of the frontend `parseVolumeAnnotations` (infer.ts): ` /// volume: ` lines in the leading comment block, each an `rw` volume -/// asset. Scanning stops at the first non-comment line; blank lines and PHP's +/// asset (`r` for `volume:ro `). Scanning stops at the first non-comment line; blank lines and PHP's /// opening tag line are skipped whole (the tag may carry code, so an annotation /// must sit on its own line below it), exactly like the frontend. fn parse_volume_annotations(content: &str, prefix: &str) -> Vec { @@ -106,11 +106,16 @@ fn parse_volume_annotations(content: &str, prefix: &str) -> Vec`; with a space after the colon, `ro` is the volume's name + let (access_type, rest) = match rest.strip_prefix("ro") { + Some(r) if r.starts_with(char::is_whitespace) => (AssetUsageAccessType::R, r), + _ => (AssetUsageAccessType::RW, rest), + }; if let Some(path) = rest.trim().split_whitespace().next() { volumes.push(AssetWithAltAccessType { path: path.to_string(), kind: AssetKind::Volume, - access_type: Some(AssetUsageAccessType::RW), + access_type: Some(access_type), alt_access_type: None, columns: None, }); @@ -266,6 +271,24 @@ mod tests { assert_eq!(vols[0].access_type, Some(AssetUsageAccessType::RW)); } + #[test] + fn read_only_volume_annotation_is_a_read() { + let content = "// volume:ro models /opt/models\n// volume: ro /tmp/ro\nconsole.log(1)\n"; + let got = effective_script_assets(&ScriptLang::Bun, content, None).unwrap(); + let vols: Vec<_> = got + .iter() + .filter(|a| a.kind == AssetKind::Volume) + .map(|a| (a.path.as_str(), a.access_type)) + .collect(); + assert_eq!( + vols, + vec![ + ("models", Some(AssetUsageAccessType::R)), + ("ro", Some(AssetUsageAccessType::RW)) + ] + ); + } + #[test] fn php_volume_annotations_survive_the_open_tag() { let content = " Router { .route("/delete/h/{hash}", post(delete_script_by_hash)) .route("/delete/p/{*path}", post(delete_script_by_path)) .route("/delete_bulk", delete(delete_scripts_bulk)) + // By hash, a script is read without the folder/path ACL that `/get/p` and `/raw/p` + // apply (`get/h` only does with `?authed=true`), and `raw/h` also skips the token-scope + // check. Ideally these would be authorized too, but the hash acts as the secret: a member + // reaching one (e.g. via a flow they can read) is by design, not a vulnerability. .route("/get/h/{hash}", get(get_script_by_hash)) .route("/raw/h/{hash}", get(raw_script_by_hash)) .route("/deployment_status/h/{hash}", get(get_deployment_status)) @@ -144,6 +152,7 @@ pub fn workspaced_service() -> Router { // CI test results .route("/ci_test_results/{kind}/{*path}", get(get_ci_test_results)) .route("/ci_test_results_batch", post(get_ci_test_results_batch)) + .route("/trigger_ci_tests_batch", post(trigger_ci_tests_batch)) // Save-time schema-contract check (pipelines gap #2b) .route("/check_schema_contracts", post(check_schema_contracts)) } @@ -575,6 +584,7 @@ async fn create_snapshot_script( user_db.clone(), webhook.clone(), query.skip_if_noop, + query.skip_ci_tests, None, ) .await?; @@ -668,6 +678,9 @@ struct CreateScriptQuery { /// sync / promotion callbacks are suppressed. #[serde(default)] skip_if_noop: bool, + /// See `windmill_dep_map::ci_tests::SkipCiTestsQuery`; also carried to the dependency job. + #[serde(default)] + skip_ci_tests: bool, } async fn create_script( @@ -686,6 +699,7 @@ async fn create_script( db, w_id, query.skip_if_noop, + query.skip_ci_tests, ns, None, ) @@ -727,6 +741,7 @@ async fn update_script( db, w_id, query.skip_if_noop, + query.skip_ci_tests, ns, Some(path.to_string()), ) @@ -740,6 +755,7 @@ async fn deploy_script( db: DB, w_id: String, skip_if_noop: bool, + skip_ci_tests: bool, ns: NewScript, supersede_head_at: Option, ) -> Result<(StatusCode, String)> { @@ -769,6 +785,7 @@ async fn deploy_script( user_db, webhook, skip_if_noop, + skip_ci_tests, supersede_head_at, ) .await?; @@ -796,7 +813,7 @@ async fn deploy_script( } hdm.handle(&db).await?; let db2 = db.clone(); - if ready_to_test { + if ready_to_test && !skip_ci_tests { tokio::spawn(async move { if let Err(e) = windmill_dep_map::ci_tests::trigger_ci_tests_for_item( &db2, @@ -1347,6 +1364,7 @@ async fn create_script_internal<'c>( user_db: UserDB, webhook: WebhookShared, skip_if_noop: bool, + skip_ci_tests: bool, // When set, the parent is the live head at this path rather than anything the body // named, resolved against the deploying transaction. supersede_head_at: Option, @@ -3048,13 +3066,15 @@ async fn create_script_internal<'c>( // Its dependency job is tagged for a dedicated worker. One taking it through a // `dedicated_workers` pattern only listens to the scripts it found at its last config // load: re-saving the group's config reloads it, unless the live version it replaces - // was served already (a version adopted from a deleted path was not). + // was served already (a version adopted from a deleted path was not). An entry's one + // leading `/` is dropped first, as `WorkspacedPath::dedicated` reads it for the worker. sqlx::query( "UPDATE config SET config = config WHERE name LIKE 'worker\\_\\_%' AND jsonb_typeof(config->'dedicated_workers') = 'array' AND EXISTS ( - SELECT 1 FROM jsonb_array_elements_text(config->'dedicated_workers') e + SELECT 1 FROM jsonb_array_elements_text(config->'dedicated_workers') raw, + regexp_replace(raw, '^([^:]*):/(?!/)', '\\1:') e WHERE right(e, 2) = '/*' AND starts_with($1 || ':' || $2, left(e, -1))) AND NOT EXISTS ( SELECT 1 FROM script WHERE workspace_id = $1 AND hash = $3 AND path = $2 @@ -3086,6 +3106,9 @@ async fn create_script_internal<'c>( if let Some(ref p_path) = p_path_opt { args.insert("parent_path".to_string(), to_raw_value(&p_path)); } + if skip_ci_tests { + args.insert("skip_ci_tests".to_string(), to_raw_value(&true)); + } let tx = PushIsolationLevel::Transaction(tx); let (job_id, mut new_tx) = windmill_queue::push( @@ -3166,12 +3189,18 @@ async fn create_script_internal<'c>( let deployment_message = ns.deployment_message.clone(); let content = ns.content.clone(); let language = ns.language.clone(); + let relock_args = skip_ci_tests.then(|| { + sqlx::types::Json(HashMap::from([( + "skip_ci_tests".to_string(), + to_raw_value(&true), + )])) + }); tokio::spawn(async move { - tokio::time::sleep(std::time::Duration::from_secs(10)).await; + tokio::time::sleep(windmill_dep_map::ci_tests::LOCKED_DEPLOY_RELOCK_DELAY).await; if let Err(e) = process_relative_imports( &db2, None, - None, + relock_args.as_ref(), &w_id2, &script_path2, parent_path, @@ -5042,14 +5071,71 @@ async fn get_ci_test_results( } #[derive(Deserialize)] -struct CiTestBatchItem { - path: String, - kind: String, +struct CiTestBatchRequest { + items: Vec, } #[derive(Deserialize)] -struct CiTestBatchRequest { +struct TriggerCiTestsBatchRequest { items: Vec, + #[serde(default)] + ignore_pending: bool, +} + +async fn trigger_ci_tests_batch( + authed: ApiAuthed, + Extension(db): Extension, + Path(w_id): Path, + Json(req): Json, +) -> JsonResult { + // The tests run as the caller, as a deploy runs them as the deployer, so queueing them + // takes a role that may run and the authority deploying the items does: the tests can be + // ones the caller cannot read. No cap on the items: a batch is as large as its push. + windmill_common::workspaces::check_role_can_run(&db, &w_id, &authed).await?; + for item in &req.items { + let (perms_query, scope) = match item.kind.as_str() { + "script" => ( + "SELECT extra_perms FROM script WHERE path = $1 AND workspace_id = $2 \ + ORDER BY created_at DESC LIMIT 1", + "scripts", + ), + "flow" => ( + "SELECT extra_perms FROM flow WHERE path = $1 AND workspace_id = $2", + "flows", + ), + "resource" => ( + "SELECT extra_perms FROM resource WHERE path = $1 AND workspace_id = $2", + "resources", + ), + other => { + return Err(Error::BadRequest(format!( + "CI tests cannot target an item of kind {other}" + ))) + } + }; + check_scopes(&authed, || format!("{scope}:write:{}", item.path))?; + require_is_writer( + &authed, + &item.path, + &w_id, + db.clone(), + perms_query, + &item.kind, + ) + .await?; + } + + Ok(Json( + windmill_dep_map::ci_tests::trigger_ci_tests_for_batch( + &db, + &w_id, + req.items, + req.ignore_pending, + &authed.email, + &authed.username, + ) + .await?, + )) } async fn get_ci_test_results_batch( diff --git a/backend/windmill-api-settings/Cargo.toml b/backend/windmill-api-settings/Cargo.toml index 816a2223ac..85b72fbae7 100644 --- a/backend/windmill-api-settings/Cargo.toml +++ b/backend/windmill-api-settings/Cargo.toml @@ -16,6 +16,7 @@ enterprise = ["license"] private = ["windmill-common/private", "windmill-audit/private"] parquet = ["windmill-common/parquet", "windmill-object-store/parquet"] license = ["dep:rsa", "dep:ed25519-dalek"] +oauth2 = ["dep:windmill-oauth"] [dependencies] windmill-ai = { workspace = true, default-features = false } @@ -42,3 +43,4 @@ sha2.workspace = true rsa = { workspace = true, optional = true } ed25519-dalek = { workspace = true, optional = true } windmill-object-store.workspace = true +windmill-oauth = { workspace = true, optional = true } diff --git a/backend/windmill-api-settings/src/lib.rs b/backend/windmill-api-settings/src/lib.rs index 6ed4e5ae48..bc17ffcf51 100644 --- a/backend/windmill-api-settings/src/lib.rs +++ b/backend/windmill-api-settings/src/lib.rs @@ -824,7 +824,7 @@ pub async fn delete_global_setting(db: &DB, key: &str) -> error::Result<()> { Ok(()) } /// Returns true when `key` is one of the workspace-fairness settings whose -/// writes must be gated to cloud only. +/// writes require an Enterprise license. fn is_workspace_fairness_setting(key: &str) -> bool { matches!( key, @@ -1007,6 +1007,20 @@ async fn run_setting_pre_write_hook( value: &serde_json::Value, ) -> error::Result<()> { match key { + #[cfg(feature = "oauth2")] + windmill_common::global_settings::OAUTH_SETTING => { + let previous = windmill_common::global_settings::load_value_from_global_settings( + db, + windmill_common::global_settings::OAUTH_SETTING, + ) + .await?; + windmill_oauth::validate_oauths_setting( + value, + previous.as_ref(), + include_str!("../../oauth_connect.json"), + ) + .map_err(|e| error::Error::BadRequest(format!("OAuth settings: {e}")))?; + } 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() => {} @@ -1505,6 +1519,9 @@ pub async fn get_global_setting( // would be refused, and they are usually not a superadmin. Not a secret: pointing // any MCP client at the instance discovers the same answer. && key != MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING + // A devops editing a worker group reads it to know whether a fairness reserve would + // ever pull a job. + && key != WORKSPACE_FAIRNESS_ENABLED_SETTING { require_super_admin(&db, &authed).await?; } diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index ba1e4bc236..e5825679cc 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -1315,6 +1315,10 @@ async fn join_workspace<'c>( async fn leave_instance(Extension(db): Extension, authed: ApiAuthed) -> Result { forbid_job_token_account_destruction(&authed)?; let mut tx = db.begin().await?; + revoke_mcp_oauth_grants(&mut *tx, &authed.email, None).await?; + sqlx::query!("DELETE FROM token WHERE email = $1", &authed.email) + .execute(&mut *tx) + .await?; sqlx::query!("DELETE FROM password WHERE email = $1", &authed.email) .execute(&mut *tx) .await?; diff --git a/backend/windmill-api-workspaces/src/remote_deploy.rs b/backend/windmill-api-workspaces/src/remote_deploy.rs index a0f922a607..070e138154 100644 --- a/backend/windmill-api-workspaces/src/remote_deploy.rs +++ b/backend/windmill-api-workspaces/src/remote_deploy.rs @@ -462,9 +462,9 @@ async fn connect( // No lock against removals, target changes or key rotations: `load_connection` voids a row // that lands after one of them. A disconnect or a newer connect stamps the row itself, which // this one then leaves alone. Without a membership to bind to, the row is bound to the account - // through the credential making this request, which deleting the account removes (except - // through `leave_instance`, which leaves its tokens): the address could otherwise be deleted - // and taken by a new account while the remote call runs, and the foreign key would accept it. + // through the credential making this request, which deleting or leaving the account removes: + // the address could otherwise be deleted and taken by a new account while the remote call + // runs, and the foreign key would accept it. let mut tx = db.begin().await?; let connected_at = sqlx::query_scalar!( "INSERT INTO remote_deploy_token diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 2d192e3b8a..e5044cdb8a 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -7656,6 +7656,14 @@ async fn clone_workspace_data( // drafts would belong to someone the fork holds no membership for. clone_drafts(tx, source_workspace_id, target_workspace_id, &authed.email).await?; + clone_favorites( + tx, + source_workspace_id, + target_workspace_id, + &authed.username, + ) + .await?; + // Clone workspace runnable dependencies and dependency map clone_workspace_runnable_dependencies(tx, source_workspace_id, target_workspace_id).await?; @@ -8661,6 +8669,70 @@ fn principal_resolves_sql(principal: &str) -> String { ) } +/// The draft half of `repoint_unresolvable_cloned_identities`: an app policy or trigger in a draft +/// copied into `target_workspace_id` that names nobody there is re-pointed at `authed`. `items` +/// narrows it to `authed`'s own rows at those keys, for drafts copied into an existing workspace. +/// +/// **Authorizes nothing itself.** The caller must have checked that `authed` (loaded in +/// `target_workspace_id`) may write those drafts there. `items = None` rewrites every draft in the +/// workspace, other users' included, so it is only for a fork being created inside the same +/// transaction, before anyone else has drafts in it. +pub async fn repoint_unresolvable_draft_identities( + tx: &mut Transaction<'_, Postgres>, + target_workspace_id: &str, + authed: &ApiAuthed, + items: Option<&[(windmill_common::user_drafts::UserDraftItemKind, String)]>, +) -> Result<()> { + let principal = username_to_permissioned_as(&authed.username); + let kinds: Option> = items.map(|i| i.iter().map(|(k, _)| k.as_str()).collect()); + let paths: Option> = items.map(|i| i.iter().map(|(_, p)| p.as_str()).collect()); + + // A draft holding a genuine NUL escape (the rule of `json_text_has_nul_escape`) is left as it + // is, since parsing it would abort the fork. The check must stay in a CASE: json `->>` raises on + // a NUL anywhere in the value, and Postgres reorders plain AND conditions. + let nul_escape = r"(^|[^\\])(\\\\)*\\u0000"; + sqlx::query(&format!( + "UPDATE draft SET value = to_json(jsonb_set(jsonb_set(to_jsonb(value), + ARRAY['policy', 'on_behalf_of'], to_jsonb($2::text)), + ARRAY['policy', 'on_behalf_of_email'], to_jsonb($3::text))) + WHERE workspace_id = $1 AND typ IN ('app', 'raw_app') + AND ($5::text[] IS NULL OR (email = $7 + AND (typ::text, path) IN (SELECT * FROM unnest($5::text[], $6::text[])))) + AND CASE WHEN value::text ~ $4 THEN false + ELSE value->'policy'->>'on_behalf_of' IS NOT NULL AND NOT ({}) END", + principal_resolves_sql("(value->'policy'->>'on_behalf_of')") + )) + .bind(target_workspace_id) + .bind(&principal) + .bind(&authed.email) + .bind(nul_escape) + .bind(kinds.as_deref()) + .bind(paths.as_deref()) + .bind(&authed.email) + .execute(&mut **tx) + .await?; + + sqlx::query(&format!( + "UPDATE draft SET value = to_json(jsonb_set(to_jsonb(value), + ARRAY['permissioned_as'], to_jsonb($2::text))) + WHERE workspace_id = $1 AND starts_with(typ::text, 'trigger_') + AND ($4::text[] IS NULL OR (email = $6 + AND (typ::text, path) IN (SELECT * FROM unnest($4::text[], $5::text[])))) + AND CASE WHEN value::text ~ $3 THEN false + ELSE value->>'permissioned_as' IS NOT NULL AND NOT ({}) END", + principal_resolves_sql("(value->>'permissioned_as')") + )) + .bind(target_workspace_id) + .bind(&principal) + .bind(nul_escape) + .bind(kinds.as_deref()) + .bind(paths.as_deref()) + .bind(&authed.email) + .execute(&mut **tx) + .await?; + Ok(()) +} + /// Re-point the identities a fork clones verbatim at its creator when they name nobody in the fork, /// once its membership is final so copied members keep theirs. Unlike scripts and flows these /// cannot drop the identity: an app deploy rejects a preserved one that does not resolve, and @@ -8685,39 +8757,7 @@ async fn repoint_unresolvable_cloned_identities( .execute(&mut **tx) .await?; - // A draft holding a genuine NUL escape (the rule of `json_text_has_nul_escape`) is left as it - // is, since parsing it would abort the fork. The check must stay in a CASE: json `->>` raises on - // a NUL anywhere in the value, and Postgres reorders plain AND conditions. - let nul_escape = r"(^|[^\\])(\\\\)*\\u0000"; - sqlx::query(&format!( - "UPDATE draft SET value = to_json(jsonb_set(jsonb_set(to_jsonb(value), - ARRAY['policy', 'on_behalf_of'], to_jsonb($2::text)), - ARRAY['policy', 'on_behalf_of_email'], to_jsonb($3::text))) - WHERE workspace_id = $1 AND typ IN ('app', 'raw_app') - AND CASE WHEN value::text ~ $4 THEN false - ELSE value->'policy'->>'on_behalf_of' IS NOT NULL AND NOT ({}) END", - principal_resolves_sql("(value->'policy'->>'on_behalf_of')") - )) - .bind(target_workspace_id) - .bind(&principal) - .bind(&authed.email) - .bind(nul_escape) - .execute(&mut **tx) - .await?; - - sqlx::query(&format!( - "UPDATE draft SET value = to_json(jsonb_set(to_jsonb(value), - ARRAY['permissioned_as'], to_jsonb($2::text))) - WHERE workspace_id = $1 AND starts_with(typ::text, 'trigger_') - AND CASE WHEN value::text ~ $3 THEN false - ELSE value->>'permissioned_as' IS NOT NULL AND NOT ({}) END", - principal_resolves_sql("(value->>'permissioned_as')") - )) - .bind(target_workspace_id) - .bind(&principal) - .bind(nul_escape) - .execute(&mut **tx) - .await?; + repoint_unresolvable_draft_identities(tx, target_workspace_id, authed, None).await?; let column_resolves = principal_resolves_sql("permissioned_as"); @@ -9265,58 +9305,45 @@ async fn clone_raw_apps( Ok(()) } -/// Clone every per-user draft (and the legacy NULL-email workspace draft, -/// if present) from the parent. The fork target is empty at create time so -/// a plain INSERT is safe — no need to UPSERT against the partial unique -/// indexes (`draft_pkey_with_user` / `draft_pkey_legacy`). `id` is the -/// BIGSERIAL synthetic PK and is regenerated by the default; we don't list -/// it in the column set. `created_at` is preserved so the per-tab -/// `last_sync` baseline the editor reads (`?get_draft=true` → overlay's -/// `draft_saved_at`) lines up with the parent's timeline — otherwise the -/// fork's first POST from any open editor would race a stale `last_sync` -/// and trip the conflict modal on every cloned draft. // Only `email = authed_email` and the legacy NULL row are cloned — see -// `clone_workspace_data` for the rationale. +// `clone_workspace_data` for the rationale. The fork is empty at create time, so +// `copy_drafts_to_workspace` skips nothing here. async fn clone_drafts( tx: &mut Transaction<'_, Postgres>, source_workspace_id: &str, target_workspace_id: &str, authed_email: &str, ) -> Result<()> { - // A script/flow draft carries the principal in its value, and deploying it in the clone - // would send a pair naming somebody who is not a member there. Stripped rather than - // filtered like `clone_scripts`: the address the draft still carries re-derives the - // clone's own principal at deploy time, which is the more accurate answer of the two. - sqlx::query!( - // A script hash is content-addressed and copied as-is, so a script draft's base - // still names a version the clone has. `clone_flows` / `clone_apps` mint new ids, - // so those drafts arrive with no base (staleness falls back to the timestamps), - // lineage field included, or the next autosave would re-derive the source id. - // - // `clean` is `strip_json_nul`'s parity rule in SQL, so a pre-sanitizer U+0000 - // escape cannot abort the clone on `to_jsonb` or arrive with its principal - // unstripped: escaped backslashes park on chr(1) (lossless, a `json` value's text - // cannot hold a raw control byte) so only a real NUL is removed, and chr(92) - // spells the backslash so no escape sequence reaches this source file. - r#"INSERT INTO draft (workspace_id, path, typ, value, created_at, email, base) - SELECT $2, path, typ, - to_json( - CASE WHEN typ IN ('script', 'flow') THEN clean - 'on_behalf_of' ELSE clean END - - CASE WHEN typ = 'flow' THEN 'version_id' - WHEN typ IN ('app', 'raw_app') THEN 'parent_version' - ELSE '' END - ), - created_at, email, - CASE WHEN typ = 'script' THEN base END - FROM ( - SELECT d.path, d.typ, d.created_at, d.email, d.base, - replace(replace(replace(d.value::text, chr(92) || chr(92), chr(1)), chr(92) || 'u0000', ''), chr(1), chr(92) || chr(92))::jsonb AS clean - FROM draft d - WHERE d.workspace_id = $1 AND (d.email = $3 OR d.email IS NULL) - ) s"#, + windmill_common::user_drafts::copy_drafts_to_workspace( + &mut **tx, source_workspace_id, target_workspace_id, authed_email, + None, + ) + .await?; + Ok(()) +} + +/// Favorites of the fork's members, read after the membership is copied. The forker is named +/// apart: a superadmin can fork a workspace without having a `usr` row in it. +async fn clone_favorites( + tx: &mut Transaction<'_, Postgres>, + source_workspace_id: &str, + target_workspace_id: &str, + forker_username: &str, +) -> Result<()> { + // Deleting a workspace leaves its favorites, so a re-used fork id can already hold some. + sqlx::query!( + "INSERT INTO favorite (usr, workspace_id, path, favorite_kind) + SELECT f.usr, $2::varchar, f.path, f.favorite_kind + FROM favorite f + WHERE f.workspace_id = $1 + AND (f.usr = $3 OR f.usr IN (SELECT username FROM usr WHERE workspace_id = $2)) + ON CONFLICT DO NOTHING", + source_workspace_id, + target_workspace_id, + forker_username, ) .execute(&mut **tx) .await?; @@ -11641,6 +11668,20 @@ pub(crate) async fn archive_workspace_impl( windmill_queue::schedule::clear_schedule(&mut tx, schedule_path, w_id).await?; } + // Public apps are served without a session, so nothing else about an archived workspace + // stops them: take them private. `publisher`, not `viewer`: viewer mode runs as whoever opens + // the app and skips its runnable allowlist, which an operator-built app must never get. + // Unarchiving does not restore them. + let unpublished_apps = sqlx::query!( + "UPDATE app SET policy = jsonb_set(policy, '{execution_mode}', '\"publisher\"') + WHERE workspace_id = $1 AND policy->>'execution_mode' = 'anonymous'", + w_id + ) + .execute(&mut *tx) + .await? + .rows_affected(); + tracing::info!("Made {unpublished_apps} public apps private in workspace {w_id}"); + // Delete non-session tokens scoped to this workspace let deleted_tokens = sqlx::query_scalar!( "DELETE FROM token WHERE workspace_id = $1 AND label IS DISTINCT FROM 'session' RETURNING token_prefix", @@ -14366,6 +14407,7 @@ async fn load_workspace_authed( job_id: base_authed.job_id, credential_expiry: base_authed.credential_expiry, mcp_client: base_authed.mcp_client.clone(), + capabilities: None, }); }; @@ -14407,6 +14449,7 @@ async fn load_workspace_authed( job_id: base_authed.job_id, credential_expiry: base_authed.credential_expiry, mcp_client: base_authed.mcp_client.clone(), + capabilities: None, }) } diff --git a/backend/windmill-api/Cargo.toml b/backend/windmill-api/Cargo.toml index 925fad6549..5d6229b892 100644 --- a/backend/windmill-api/Cargo.toml +++ b/backend/windmill-api/Cargo.toml @@ -37,7 +37,7 @@ smtp = ["instance_smtp", "dep:mail-parser", "dep:openssl", "dep:windmill-trigger instance_smtp = ["windmill-common/smtp"] license = ["dep:rsa", "windmill-api-settings/license"] zip = ["dep:async_zip"] -oauth2 = ["dep:windmill-oauth", "windmill-store/oauth2"] +oauth2 = ["dep:windmill-oauth", "windmill-store/oauth2", "windmill-api-settings/oauth2"] http_trigger = ["dep:matchit", "dep:windmill-trigger-http", "windmill-store/http_trigger", "dep:windmill-api-openapi"] static_frontend = ["dep:rust-embed"] postgres_trigger = ["dep:windmill-trigger-postgres", "windmill-store/postgres_trigger"] diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 2602b2a685..39d0328c63 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.866.0 + version: 1.880.1 title: Windmill API contact: @@ -9184,6 +9184,7 @@ paths: type: boolean has_shared_credentials: type: boolean + description: The instance entry holds a client id and secret users can connect with, for sign-in or as a shared service account. Whether client credentials are shared is get_connect's client_credentials_configured. required: - name - supports_client_credentials @@ -9224,6 +9225,37 @@ paths: type: boolean description: "The instance OAuth entry carries shared client-credentials, so the connect dialog can skip the bring-your-own form and run the exchange server-side" + /oauth/test_client_credentials: + post: + summary: test an instance OAuth entry's client credentials + description: Runs the client-credentials token exchange with an instance OAuth entry, saved or not. Superadmin only. + operationId: testOAuthClientCredentials + tags: + - oauth + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + name: + type: string + description: client name, the key of the entry in the instance OAuth setting + entry: + type: object + description: the entry as stored in the instance OAuth setting + required: + - name + - entry + responses: + "200": + description: the exchange returned a token + content: + text/plain: + schema: + type: string + /teams/activities: post: summary: send update to Microsoft Teams activity @@ -9264,6 +9296,7 @@ paths: summary: create resource operationId: createResource x-mcp-tool: true + x-mcp-tool-include-query-params: [update_if_exists] tags: - resource parameters: @@ -9273,6 +9306,7 @@ paths: in: query schema: type: boolean + - $ref: "#/components/parameters/SkipCiTests" requestBody: description: new resource required: true @@ -9343,11 +9377,13 @@ paths: summary: update resource operationId: updateResource x-mcp-tool: true + x-mcp-tool-include-query-params: [] tags: - resource parameters: - $ref: "#/components/parameters/WorkspaceId" - $ref: "#/components/parameters/Path" + - $ref: "#/components/parameters/SkipCiTests" requestBody: description: updated resource required: true @@ -11061,40 +11097,7 @@ paths: schema: type: array items: - allOf: - - $ref: "#/components/schemas/Script" - - type: object - properties: - is_draft: - type: boolean - description: | - True when the authed user has a draft for this - script — either no deployed row exists at this - path (draft-only) or the user saved a per-user - draft on top of the deployed row. - draft_path: - type: string - description: | - User-typed path the editor has staged but not - yet deployed. Surfaced for draft-only rows so - the home list can render the meaningful name - instead of the autogenerated - `u/{user}/draft_{uuid}` URL path. Omitted - when unchanged. - draft_users: - description: | - Workspace users (including the authed user, and - the legacy NULL-email row if any) who have a - per-user draft at this path. Drives the home - page's user-avatar circles inside the Draft - badge. Omitted when no drafts exist. - type: array - items: - type: object - properties: - username: - type: string - nullable: true + $ref: "#/components/schemas/ListableScript" /w/{workspace}/scripts/list_paths: get: @@ -11148,10 +11151,13 @@ paths: type: string summary: type: string - description: Best-effort, read from the draft JSON's `summary` field when the editor shape carries one. + description: Best-effort, read from the draft JSON's `summary` field when the editor shape carries one, or its `description` for an agent's draft. draft_path: type: string description: User-typed friendly path from the draft JSON's `draft_path`, when set and different from the storage path (e.g. a never-deployed item parked at `u/{user}/draft_{uuid}`). + resource_type: + type: string + description: A `resource` draft's type, the deployed row's when there is one, else the one the draft names. `ai_agent` marks an agent's draft. draft_only: type: boolean description: No deployed counterpart exists at this path — the draft is the whole item. @@ -11375,6 +11381,56 @@ paths: schema: type: string + /w/{workspace}/drafts/transfer: + post: + summary: copy the current user's drafts into another workspace of the family and/or remove them here + description: In one transaction, copies the authed user's own drafts of `items` into `target_workspace` (another workspace of this one's family, with the same root through `parent_workspace_id`) and, with `remove_from_source`, deletes them here. Without `target_workspace` it only removes. If the user already has a draft of any item in the target, nothing is written and the items are returned in `conflicts`, unless `replace_existing` is set. A user who can only compose flows or apps in the target is held to the same rules as a direct draft save there. + operationId: transferDrafts + tags: + - draft + parameters: + - $ref: "#/components/parameters/WorkspaceId" + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + target_workspace: + type: string + items: + type: array + items: + $ref: "#/components/schemas/DraftItemRef" + remove_from_source: + type: boolean + replace_existing: + type: boolean + description: Overwrite the user's own drafts of `items` already in the target instead of returning them as conflicts. + required: [items] + responses: + "200": + description: transfer result + content: + application/json: + schema: + type: object + properties: + copied: + type: array + items: + $ref: "#/components/schemas/DraftItemRef" + removed: + type: array + items: + $ref: "#/components/schemas/DraftItemRef" + conflicts: + type: array + items: + $ref: "#/components/schemas/DraftItemRef" + required: [copied, removed, conflicts] + /w/{workspace}/drafts/migrate_legacy/{kind}/{path}: post: summary: resolve a legacy (workspace-level) draft (admin only) @@ -11433,10 +11489,12 @@ paths: - schema x-mcp-tool-opaque-fields: - schema + x-mcp-tool-include-query-params: [] tags: - script parameters: - $ref: "#/components/parameters/WorkspaceId" + - $ref: "#/components/parameters/SkipCiTests" requestBody: description: Partially filled script required: true @@ -11475,11 +11533,13 @@ paths: - schema x-mcp-tool-opaque-fields: - schema + x-mcp-tool-include-query-params: [] tags: - script parameters: - $ref: "#/components/parameters/WorkspaceId" - $ref: "#/components/parameters/ScriptPath" + - $ref: "#/components/parameters/SkipCiTests" requestBody: description: The new version of the script, whose `path` is where it should end up. required: true @@ -12243,6 +12303,59 @@ paths: items: $ref: "#/components/schemas/CiTestResult" + /w/{workspace}/scripts/trigger_ci_tests_batch: + post: + summary: queue the CI tests of a batch of deploys + description: | + Queues the CI tests of items deployed with `skip_ci_tests`, plus those of the scripts + importing them, once nothing those tests read (the tested items, the test scripts and + their imports) still has a dependency job queued or running. While one does, nothing is + queued and `pending` lists those paths: call again later, or pass `ignore_pending` to + queue them anyway. The tests run as the caller, who must be able to deploy each item. + operationId: triggerCiTestsBatch + tags: + - script + parameters: + - $ref: "#/components/parameters/WorkspaceId" + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + items: + type: array + items: + type: object + properties: + path: + type: string + kind: + type: string + enum: [script, flow, resource] + required: [path, kind] + ignore_pending: + type: boolean + required: [items] + responses: + "200": + description: the paths still pending, and the CI test jobs queued + content: + application/json: + schema: + type: object + properties: + pending: + type: array + items: + type: string + job_ids: + type: array + items: + type: string + format: uuid + required: [pending, job_ids] /w/{workspace}/scripts/check_schema_contracts: post: summary: check a script's asset references against captured producer schemas @@ -12555,6 +12668,11 @@ paths: in: query schema: type: string + - name: take_over + description: Stop the run that holds `memory_id`, if any, and run this one instead of being refused with a 409. Only who started that run, or an admin, can stop it; a restricted token also needs an unconfined `jobs:cancel` scope. + in: query + schema: + type: boolean requestBody: description: script args @@ -12572,9 +12690,10 @@ paths: schema: {} "409": description: >- - Chat-enabled flow only: the conversation named by `memory_id` is still answering - a message. The body is JSON: `{ "error": string, "running_turn": { "job_id", - "user_seq" } }`. + Another run with this `memory_id` is still running (for a chat-enabled flow, the + conversation is still answering a message). The body is JSON: `{ "error": string, + "running_turn": { "job_id", "user_seq"? } }`, `user_seq` for a chat conversation. + Pass `take_over=true` to stop it instead. /w/{workspace}/jobs/run_wait_result/fv/{version}: post: @@ -12600,6 +12719,11 @@ paths: in: query schema: type: string + - name: take_over + description: Stop the run that holds `memory_id`, if any, and run this one instead of being refused with a 409. Only who started that run, or an admin, can stop it; a restricted token also needs an unconfined `jobs:cancel` scope. + in: query + schema: + type: boolean requestBody: description: script args @@ -12617,9 +12741,10 @@ paths: schema: {} "409": description: >- - Chat-enabled flow only: the conversation named by `memory_id` is still answering - a message. The body is JSON: `{ "error": string, "running_turn": { "job_id", - "user_seq" } }`. + Another run with this `memory_id` is still running (for a chat-enabled flow, the + conversation is still answering a message). The body is JSON: `{ "error": string, + "running_turn": { "job_id", "user_seq"? } }`, `user_seq` for a chat conversation. + Pass `take_over=true` to stop it instead. get: summary: run flow by version with GET and wait until completion @@ -12645,6 +12770,11 @@ paths: in: query schema: type: string + - name: take_over + description: Stop the run that holds `memory_id`, if any, and run this one instead of being refused with a 409. Only who started that run, or an admin, can stop it; a restricted token also needs an unconfined `jobs:cancel` scope. + in: query + schema: + type: boolean responses: "200": @@ -12654,9 +12784,10 @@ paths: schema: {} "409": description: >- - Chat-enabled flow only: the conversation named by `memory_id` is still answering - a message. The body is JSON: `{ "error": string, "running_turn": { "job_id", - "user_seq" } }`. + Another run with this `memory_id` is still running (for a chat-enabled flow, the + conversation is still answering a message). The body is JSON: `{ "error": string, + "running_turn": { "job_id", "user_seq"? } }`, `user_seq` for a chat conversation. + Pass `take_over=true` to stop it instead. /w/{workspace}/jobs/run_and_stream/f/{path}: post: @@ -12676,6 +12807,11 @@ paths: in: query schema: type: string + - name: take_over + description: Stop the run that holds `memory_id`, if any, and run this one instead of being refused with a 409. Only who started that run, or an admin, can stop it; a restricted token also needs an unconfined `jobs:cancel` scope. + in: query + schema: + type: boolean - name: poll_delay_ms description: delay between polling for job updates in milliseconds in: query @@ -12700,9 +12836,10 @@ paths: type: string "409": description: >- - Chat-enabled flow only: the conversation named by `memory_id` is still answering - a message. The body is JSON: `{ "error": string, "running_turn": { "job_id", - "user_seq" } }`. + Another run with this `memory_id` is still running (for a chat-enabled flow, the + conversation is still answering a message). The body is JSON: `{ "error": string, + "running_turn": { "job_id", "user_seq"? } }`, `user_seq` for a chat conversation. + Pass `take_over=true` to stop it instead. get: summary: run flow by path with GET and stream updates via SSE @@ -12722,6 +12859,11 @@ paths: in: query schema: type: string + - name: take_over + description: Stop the run that holds `memory_id`, if any, and run this one instead of being refused with a 409. Only who started that run, or an admin, can stop it; a restricted token also needs an unconfined `jobs:cancel` scope. + in: query + schema: + type: boolean - name: poll_delay_ms description: delay between polling for job updates in milliseconds in: query @@ -12738,9 +12880,10 @@ paths: type: string "409": description: >- - Chat-enabled flow only: the conversation named by `memory_id` is still answering - a message. The body is JSON: `{ "error": string, "running_turn": { "job_id", - "user_seq" } }`. + Another run with this `memory_id` is still running (for a chat-enabled flow, the + conversation is still answering a message). The body is JSON: `{ "error": string, + "running_turn": { "job_id", "user_seq"? } }`, `user_seq` for a chat conversation. + Pass `take_over=true` to stop it instead. /w/{workspace}/jobs/run_and_stream/fv/{version}: post: @@ -12766,6 +12909,11 @@ paths: in: query schema: type: string + - name: take_over + description: Stop the run that holds `memory_id`, if any, and run this one instead of being refused with a 409. Only who started that run, or an admin, can stop it; a restricted token also needs an unconfined `jobs:cancel` scope. + in: query + schema: + type: boolean - name: poll_delay_ms description: delay between polling for job updates in milliseconds in: query @@ -12790,9 +12938,10 @@ paths: type: string "409": description: >- - Chat-enabled flow only: the conversation named by `memory_id` is still answering - a message. The body is JSON: `{ "error": string, "running_turn": { "job_id", - "user_seq" } }`. + Another run with this `memory_id` is still running (for a chat-enabled flow, the + conversation is still answering a message). The body is JSON: `{ "error": string, + "running_turn": { "job_id", "user_seq"? } }`, `user_seq` for a chat conversation. + Pass `take_over=true` to stop it instead. get: summary: run flow by version with GET and stream updates via SSE @@ -12818,6 +12967,11 @@ paths: in: query schema: type: string + - name: take_over + description: Stop the run that holds `memory_id`, if any, and run this one instead of being refused with a 409. Only who started that run, or an admin, can stop it; a restricted token also needs an unconfined `jobs:cancel` scope. + in: query + schema: + type: boolean - name: poll_delay_ms description: delay between polling for job updates in milliseconds in: query @@ -12834,9 +12988,10 @@ paths: type: string "409": description: >- - Chat-enabled flow only: the conversation named by `memory_id` is still answering - a message. The body is JSON: `{ "error": string, "running_turn": { "job_id", - "user_seq" } }`. + Another run with this `memory_id` is still running (for a chat-enabled flow, the + conversation is still answering a message). The body is JSON: `{ "error": string, + "running_turn": { "job_id", "user_seq"? } }`, `user_seq` for a chat conversation. + Pass `take_over=true` to stop it instead. /w/{workspace}/jobs/run_and_stream/p/{path}: post: @@ -13011,6 +13166,137 @@ paths: application/json: schema: {} + /w/{workspace}/jobs/flow/approval_step_detail/{job_id}/{step_id}: + get: + summary: get the approval detail of one step of a flow run + description: > + Get the approval state of an approval (suspend) step of a flow run, by the + flow run id and the step id, in a single query: where the step stands, its + approval settings, the approvals received and, while it waits, whether the + caller can approve. Only the run's own steps are searched: for a step inside + a branch or loop, pass the id of the branch's or iteration's run. + operationId: getApprovalStepDetail + tags: + - job + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: job_id + in: path + required: true + description: id of the flow run + schema: + type: string + format: uuid + - name: step_id + in: path + required: true + description: id of the approval step in the flow + schema: + type: string + responses: + "200": + description: approval step detail + content: + application/json: + schema: + type: object + required: + - flow_id + - step_id + - status + - required_events + - hide_cancel + - continue_on_disapprove_timeout + - skin + - approvals + properties: + flow_id: + type: string + format: uuid + step_id: + type: string + status: + type: string + enum: [not_reached, skipped, failed, waiting, resumed, not_resumed] + description: > + not_reached: the step's own script has not finished yet. + failed: the step failed before asking for approval. + waiting: the run is suspended on this step. + resumed: the run moved past this step. + not_resumed: the run ended while waiting (denied, timed out or cancelled). + step_job: + type: string + format: uuid + description: the job of the approval step, once it ran + step_summary: + type: string + required_events: + type: integer + description: number of approvals required to resume + timeout: + type: integer + description: seconds the run waits for approvals + suspended_until: + type: string + format: date-time + description: when the wait times out, while waiting + form_schema: + description: form schema for the approval step + hide_cancel: + type: boolean + continue_on_disapprove_timeout: + type: boolean + skin: + type: string + enum: [detailed, minimal] + approval_conditions: + type: object + properties: + user_auth_required: + type: boolean + user_groups_required: + type: array + items: + type: string + self_approval_disabled: + type: boolean + required: + - user_auth_required + - user_groups_required + - self_approval_disabled + can_approve: + type: boolean + description: whether the caller can approve, set only while waiting + description: + description: description returned by the approval step's script + default_args: + description: default form values returned by the approval step's script + enums: + description: form enums returned by the approval step's script + approvals: + type: array + description: > + approvals received. approved, value and created_at are known only + while the run is live; a finished run keeps approver names alone. + items: + type: object + required: + - resume_id + - approver + properties: + resume_id: + type: integer + approver: + type: string + approved: + type: boolean + value: {} + created_at: + type: string + format: date-time + error: + description: the run's error, when status is not_resumed + /w/{workspace}/jobs/job_view_token/{id}: get: summary: mint a read-only share token for a job @@ -13144,6 +13430,11 @@ paths: description: restrict to paths under this prefix schema: type: string + - name: paths + in: query + description: comma-separated exact paths, to list only the rows at one of them + schema: + type: string - name: label in: query schema: @@ -13161,6 +13452,14 @@ paths: homepage, whose matcher discards those queries too. schema: type: string + - name: search_any_order + in: query + description: >- + when true, each search term must appear anywhere in "summary (path)", in any + order, rather than in the order given, and terms are split on anything but + letters, digits and apostrophes in any script, not only ASCII ones. + schema: + type: boolean - $ref: "#/components/parameters/PerPage" - name: cursor in: query @@ -13641,10 +13940,12 @@ paths: x-mcp-tool-opaque-fields: - value - schema + x-mcp-tool-include-query-params: [] tags: - flow parameters: - $ref: "#/components/parameters/WorkspaceId" + - $ref: "#/components/parameters/SkipCiTests" requestBody: description: Partially filled flow required: true @@ -13684,11 +13985,13 @@ paths: x-mcp-tool-opaque-fields: - value - schema + x-mcp-tool-include-query-params: [] tags: - flow parameters: - $ref: "#/components/parameters/WorkspaceId" - $ref: "#/components/parameters/ScriptPath" + - $ref: "#/components/parameters/SkipCiTests" requestBody: description: Partially filled flow required: true @@ -14099,7 +14402,9 @@ paths: user: type: string model: - description: defaults to the AI config's default model + description: > + defaults to the AI config's default model. Must be enabled in the AI + settings, or be the default, metadata or code-completion model. $ref: "#/components/schemas/AIProviderModel" max_tokens: type: integer @@ -15392,6 +15697,41 @@ paths: share: $ref: "#/components/schemas/SharedAiSessionInfo" + /w/{workspace}/ai/shared_sessions/list: + get: + summary: list the caller's shared AI sessions + description: > + The caller's own shares and the ones they opened by link, most recently shared or opened + first, without their snapshot. Capped at 500. `session_id` is set on the caller's own + shares only, `opened_at` on the others. + operationId: listSharedAiSessions + tags: + - ai + parameters: + - $ref: "#/components/parameters/WorkspaceId" + responses: + "200": + description: the shares + content: + application/json: + schema: + type: array + items: + allOf: + - $ref: "#/components/schemas/SharedAiSessionInfo" + - type: object + properties: + mine: + type: boolean + session_id: + type: string + opened_at: + type: string + format: date-time + description: when the caller last opened this share by link + required: + - mine + /w/{workspace}/ai/shared_sessions/set_public/{id}: post: summary: make a shared AI session public, or reserve it to workspace members @@ -15454,6 +15794,7 @@ paths: required: - snapshot - can_unshare + - mine properties: snapshot: type: object @@ -15461,6 +15802,33 @@ paths: can_unshare: type: boolean description: whether the caller authored the share or is a workspace admin + mine: + type: boolean + description: whether the caller authored the share + + /w/{workspace}/ai/shared_sessions/opened/{id}: + delete: + summary: remove a shared AI session from the caller's list + description: > + The share stays readable by link; opening it again lists it again. + operationId: forgetOpenedAiSession + tags: + - ai + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + "200": + description: removed from the list + content: + text/plain: + schema: + type: string /w/{workspace}/ai/shared_sessions/delete/{id}: delete: @@ -16840,6 +17208,11 @@ paths: in: query schema: type: string + - name: take_over + description: Stop the run that holds `memory_id`, if any, and run this one instead of being refused with a 409. Only who started that run, or an admin, can stop it; a restricted token also needs an unconfined `jobs:cancel` scope. + in: query + schema: + type: boolean requestBody: description: flow args required: true @@ -16857,9 +17230,10 @@ paths: format: uuid "409": description: >- - Chat-enabled flow only: the conversation named by `memory_id` is still answering - a message. The body is JSON: `{ "error": string, "running_turn": { "job_id", - "user_seq" } }`. + Another run with this `memory_id` is still running (for a chat-enabled flow, the + conversation is still answering a message). The body is JSON: `{ "error": string, + "running_turn": { "job_id", "user_seq"? } }`, `user_seq` for a chat conversation. + Pass `take_over=true` to stop it instead. /w/{workspace}/jobs/run/fv/{version}: post: @@ -16902,6 +17276,11 @@ paths: in: query schema: type: string + - name: take_over + description: Stop the run that holds `memory_id`, if any, and run this one instead of being refused with a 409. Only who started that run, or an admin, can stop it; a restricted token also needs an unconfined `jobs:cancel` scope. + in: query + schema: + type: boolean requestBody: description: flow args required: true @@ -16919,9 +17298,10 @@ paths: format: uuid "409": description: >- - Chat-enabled flow only: the conversation named by `memory_id` is still answering - a message. The body is JSON: `{ "error": string, "running_turn": { "job_id", - "user_seq" } }`. + Another run with this `memory_id` is still running (for a chat-enabled flow, the + conversation is still answering a message). The body is JSON: `{ "error": string, + "running_turn": { "job_id", "user_seq"? } }`, `user_seq` for a chat conversation. + Pass `take_over=true` to stop it instead. /w/{workspace}/jobs/run/batch_rerun_jobs: post: @@ -17382,6 +17762,60 @@ paths: type: string format: uuid + /w/{workspace}/jobs/run/flow_test/{path}: + post: + summary: run a deployed flow with some steps overridden, for tests + description: >- + Runs the latest deployed version of the flow as a flow preview, with each step named + in `steps` either mocked (`{"return_value": ...}`) or replaced by a function of the + code of `caller_job_id` (`{"function": ""}`), called with the step's inputs. + Needs the same rights as a flow preview. + operationId: runFlowTest + tags: + - job + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - $ref: "#/components/parameters/ScriptPath" + - $ref: "#/components/parameters/NewJobId" + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + args: + $ref: "#/components/schemas/ScriptArgs" + steps: + type: object + description: >- + step id -> override. A step inside a subflow is named by the path of step + ids to it, `sub:inner` for step `inner` of the subflow that step `sub` calls. + additionalProperties: + type: object + properties: + return_value: + description: the step is skipped and returns this value + function: + type: string + description: >- + name of a function of the code of `caller_job_id` that runs instead + of the step (exported, in TypeScript) + caller_job_id: + type: string + format: uuid + description: >- + the job whose code defines the replacing functions, usually the calling + test; a script run or a script preview. Required with a `function` override. + responses: + "201": + description: job created + content: + text/plain: + schema: + type: string + format: uuid + /w/{workspace}/jobs/run/preview_flow: post: summary: run flow preview @@ -17402,6 +17836,11 @@ paths: in: query schema: type: string + - name: take_over + description: Stop the run that holds `memory_id`, if any, and run this one instead of being refused with a 409. Only who started that run, or an admin, can stop it; a restricted token also needs an unconfined `jobs:cancel` scope. + in: query + schema: + type: boolean requestBody: description: preview @@ -17421,9 +17860,10 @@ paths: format: uuid "409": description: >- - Chat-enabled flow only: the conversation named by `memory_id` is still answering - a message. The body is JSON: `{ "error": string, "running_turn": { "job_id", - "user_seq" } }`. + Another run with this `memory_id` is still running (for a chat-enabled flow, the + conversation is still answering a message). The body is JSON: `{ "error": string, + "running_turn": { "job_id", "user_seq"? } }`, `user_seq` for a chat conversation. + Pass `take_over=true` to stop it instead. /w/{workspace}/jobs/run/agent/{path}: post: @@ -17445,6 +17885,11 @@ paths: in: query schema: type: string + - name: take_over + description: Stop the run that holds `memory_id`, if any, and run this one instead of being refused with a 409. Only who started that run, or an admin, can stop it; a restricted token also needs an unconfined `jobs:cancel` scope. + in: query + schema: + type: boolean requestBody: description: the run's inputs required: true @@ -17486,6 +17931,11 @@ paths: in: query schema: type: string + - name: take_over + description: Stop the run that holds `memory_id`, if any, and run this one instead of being refused with a 409. Only who started that run, or an admin, can stop it; a restricted token also needs an unconfined `jobs:cancel` scope. + in: query + schema: + type: boolean requestBody: description: preview @@ -17503,9 +17953,10 @@ paths: schema: {} "409": description: >- - Chat-enabled flow only: the conversation named by `memory_id` is still answering - a message. The body is JSON: `{ "error": string, "running_turn": { "job_id", - "user_seq" } }`. + Another run with this `memory_id` is still running (for a chat-enabled flow, the + conversation is still answering a message). The body is JSON: `{ "error": string, + "running_turn": { "job_id", "user_seq"? } }`, `user_seq` for a chat conversation. + Pass `take_over=true` to stop it instead. /w/{workspace}/jobs/run/dynamic_select: post: @@ -17813,6 +18264,11 @@ paths: required: false schema: type: string + - name: has_null_parent + description: has null parent + in: query + schema: + type: boolean - name: all_workspaces description: get jobs from all workspaces (only valid if request come from the `admins` workspace) in: query @@ -18989,6 +19445,9 @@ paths: type: boolean started: type: boolean + is_skipped: + type: boolean + description: set when the job is completed; true if it ended as skipped (also counted as success) required: - completed - result @@ -24440,6 +24899,9 @@ paths: properties: name: type: string + display_name: + type: string + description: Defaults to the name. summary: type: string owners: @@ -24484,6 +24946,8 @@ paths: properties: summary: type: string + display_name: + type: string owners: type: array items: @@ -25096,6 +25560,62 @@ paths: items: $ref: "#/components/schemas/AutoscalingEvent" + /configs/autoscaling_diagnostics/{worker_group}: + get: + summary: Get the recorded autoscaling decisions of a worker group, and whether a recording is running + operationId: getAutoscalingDiagnostics + tags: + - config + parameters: + - name: worker_group + in: path + required: true + schema: + type: string + - name: include_decisions + description: false returns the recording state and the decision count only + in: query + schema: + type: boolean + responses: + "200": + description: The recording state and the recorded decisions, oldest first + content: + application/json: + schema: + $ref: "#/components/schemas/AutoscalingDiagnostics" + + /configs/autoscaling_recording/{worker_group}: + post: + summary: Start recording the autoscaling decisions of a worker group for 24 hours, or stop + operationId: setAutoscalingRecording + tags: + - config + parameters: + - name: worker_group + in: path + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + record: + type: boolean + required: + - record + responses: + "200": + description: Recording started or stopped + content: + text/plain: + schema: + type: string + /configs/test_autoscaling/{worker_group}: post: summary: Run an autoscaling integration once for a worker group, without recording an autoscaling event @@ -29218,6 +29738,12 @@ components: required: true schema: type: string + SkipCiTests: + name: skip_ci_tests + description: Do not queue the CI tests of this deploy. Set by a caller deploying several items in a row, which queues them with triggerCiTestsBatch once the whole batch has landed. + in: query + schema: + type: boolean TablePreviewS3ResourcePath: name: s3_resource_path description: Read the file from this object storage resource instead of the workspace storage. @@ -30064,6 +30590,15 @@ components: surfaced in the fork modal as "Last updated". required: [draft_saved_at] required: [is_draft] + DraftItemRef: + type: object + properties: + kind: + $ref: "#/components/schemas/UserDraftItemKind" + path: + type: string + required: [kind, path] + UserDraftItemKind: type: string description: | @@ -31877,6 +32412,109 @@ components: - type - path + ListableScript: + type: object + description: | + A script as returned by the list endpoint: the deployed row's summary + fields, without its content, lock or schema. + properties: + hash: + type: string + path: + type: string + summary: + type: string + description: + type: string + created_at: + type: string + format: date-time + archived: + type: boolean + extra_perms: + type: object + additionalProperties: + type: boolean + language: + $ref: "#/components/schemas/ScriptLang" + kind: + type: string + enum: [script, failure, trigger, approval, preprocessor] + starred: + type: boolean + tag: + type: string + nullable: true + draft_only: + type: boolean + description: | + True on rows built from a draft that was never deployed. Omitted + on deployed rows. + has_deploy_errors: + type: boolean + ws_error_handler_muted: + type: boolean + nullable: true + auto_kind: + type: string + use_codebase: + type: boolean + description: Omitted when false. + deployment_msg: + type: string + description: Only returned with `with_deployment_msg=true`. + labels: + type: array + items: + type: string + inherited_labels: + type: array + items: + type: string + is_draft: + type: boolean + description: | + True when the authed user has a draft for this + script — either no deployed row exists at this + path (draft-only) or the user saved a per-user + draft on top of the deployed row. Omitted when false. + draft_path: + type: string + description: | + User-typed path the editor has staged but not + yet deployed. Surfaced for draft-only rows so + the home list can render the meaningful name + instead of the autogenerated + `u/{user}/draft_{uuid}` URL path. Omitted + when unchanged. + draft_users: + description: | + Workspace users (including the authed user, and + the legacy NULL-email row if any) who have a + per-user draft at this path. Drives the home + page's user-avatar circles inside the Draft + badge. Omitted when no drafts exist. + type: array + items: + type: object + properties: + username: + type: string + nullable: true + required: + - hash + - path + - summary + - created_at + - archived + - extra_perms + - language + - kind + - starred + - tag + - has_deploy_errors + - ws_error_handler_muted + Script: type: object properties: @@ -34144,6 +34782,12 @@ components: On a draft-only row, the path its editor has staged when it differs from the storage path (e.g. a never-deployed item parked at `u/{user}/draft_{uuid}`). + grant_type: + type: string + description: | + The grant of the linked OAuth account: `client_credentials` + connects as the app, `authorization_code` as the user who + connected it. required: - path - resource_type @@ -37888,6 +38532,8 @@ components: properties: name: type: string + display_name: + type: string owners: type: array items: @@ -39973,6 +40619,56 @@ components: type: string format: date-time + AutoscalingDiagnostics: + type: object + properties: + recording_until: + type: string + format: date-time + nullable: true + recording_started_by: + type: string + nullable: true + decision_count: + type: integer + format: int64 + decisions: + type: array + items: + $ref: "#/components/schemas/AutoscalingDecision" + required: + - decision_count + - decisions + + AutoscalingDecision: + type: object + properties: + recorded_at: + type: string + format: date-time + worker_count: + type: integer + occupancy_rate_15s: + type: number + nullable: true + occupancy_rate_5m: + type: number + nullable: true + occupancy_rate_30m: + type: number + nullable: true + jobs_waiting: + type: object + additionalProperties: + type: integer + decision: + type: string + required: + - recorded_at + - worker_count + - jobs_waiting + - decision + CriticalAlert: type: object properties: diff --git a/backend/windmill-api/src/agent_runs.rs b/backend/windmill-api/src/agent_runs.rs index 2258a2acd7..4aba0c4439 100644 --- a/backend/windmill-api/src/agent_runs.rs +++ b/backend/windmill-api/src/agent_runs.rs @@ -29,7 +29,8 @@ 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, run_end_user_email, set_flow_memory_id, RunJobQuery, + handle_chat_conversation_messages, run_end_user_email, set_flow_memory_id, + take_over_memory_turn, RunJobQuery, }; /// The id the agent's step carries in the run, as the editor's chat names it. A token scoped to @@ -72,6 +73,7 @@ pub(crate) async fn run_agent_as( let AgentTurn { flow_value, run_path, agent_obo } = agent_turn(authed, user_db, w_id, path, chat).await?; + take_over_memory_turn(db, authed, w_id, &run_path, run_query).await?; 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 @@ -144,9 +146,6 @@ pub(crate) async fn run_agent_as( ) .await?; - if let Some(memory_id) = run_query.memory_key(w_id, &run_path) { - set_flow_memory_id(&mut tx, uuid, memory_id).await?; - } if chat { // The caller's conversation, whoever the agent runs as, and a real one: this is the // agent as deployed, not a draft under test. @@ -163,6 +162,9 @@ pub(crate) async fn run_agent_as( ) .await?; } + if let Some(memory_id) = run_query.memory_key(w_id, &run_path) { + set_flow_memory_id(&mut tx, w_id, uuid, memory_id).await?; + } tx.commit().await?; Ok(uuid) diff --git a/backend/windmill-api/src/ai.rs b/backend/windmill-api/src/ai.rs index 81c6e46451..996331cb9e 100644 --- a/backend/windmill-api/src/ai.rs +++ b/backend/windmill-api/src/ai.rs @@ -39,7 +39,7 @@ use windmill_ai::providers::{ handle_google_ai_chat_proxy, handle_google_ai_models_proxy, GoogleAIProxyResponse, GoogleAIProxyResponseBody, }, - is_chat_completions_only, + is_chat_completions_only, reads_max_completion_tokens, }; use windmill_ai::proxy::{ fim::maybe_transform_fim_request, proxy_execution_mode, validate_proxy_path, ProxyBuildArgs, @@ -47,6 +47,9 @@ use windmill_ai::proxy::{ }; use windmill_ai::retry::send_with_retries; use windmill_ai::types::{OpenAIContent, OpenAIMessage}; +use windmill_ai::vertex_workload_identity::{ + check_vertex_base_url, exchange_oidc_token, GcpAccessToken, VertexWorkloadIdentity, +}; use windmill_ai::web_search::{WebPage, WebSearchProvider, WebSearchResult}; use windmill_audit::{audit_oss::audit_log, ActionKind}; use windmill_common::client::AuthedClient; @@ -132,6 +135,10 @@ lazy_static::lazy_static! { /// federation settings, user email). Like BEDROCK_ASSUMED_ROLE_CACHE, an entry /// is never handed to another user than the one the OIDC token named. static ref ANTHROPIC_FEDERATED_TOKEN_CACHE: Cache<(String, AnthropicFederation, String), FederatedAccessToken> = Cache::new(500); + + /// Google access tokens from a Vertex Workload Identity Federation exchange, + /// keyed like ANTHROPIC_FEDERATED_TOKEN_CACHE by (workspace, settings, user email). + static ref VERTEX_WORKLOAD_IDENTITY_TOKEN_CACHE: Cache<(String, VertexWorkloadIdentity, String), GcpAccessToken> = Cache::new(500); } #[cfg(feature = "bedrock")] @@ -147,6 +154,8 @@ pub(crate) fn invalidate_ai_request_cache_for_workspace(workspace_id: &str) { AI_REQUEST_CACHE.retain(|(cached_workspace_id, _), _| cached_workspace_id != workspace_id); ANTHROPIC_FEDERATED_TOKEN_CACHE .retain(|(cached_workspace_id, _, _), _| cached_workspace_id != workspace_id); + VERTEX_WORKLOAD_IDENTITY_TOKEN_CACHE + .retain(|(cached_workspace_id, _, _), _| cached_workspace_id != workspace_id); // Dropped alongside the credentials that named the role, so that changing a // workspace's AI settings does not leave a session assumed under the old ones // in play until STS expires it. @@ -249,6 +258,14 @@ struct AIStandardResource { /// Custom HTTP headers to include in AI requests #[serde(default)] headers: HashMap, + /// Set only by `vertex_ai_federated` resources, which authenticate to Vertex AI + /// through Google Cloud Workload Identity Federation. + #[serde(default, deserialize_with = "empty_string_as_none")] + workload_identity_provider: Option, + #[serde(default, deserialize_with = "empty_string_as_none")] + service_account_email: Option, + #[serde(default, deserialize_with = "empty_string_as_none")] + workload_identity_audience: Option, /// The API token of a `cloudflare` resource, which names it `token` rather than `api_key`. #[serde(default, deserialize_with = "empty_string_as_none")] token: Option, @@ -309,6 +326,19 @@ async fn resolve_var( } } +async fn resolve_optional_var( + value: Option, + db: &DB, + w_id: &str, + user_db: Option<&UserDB>, + authed: Option<&ApiAuthed>, +) -> Result> { + match value { + Some(value) => Ok(Some(resolve_var(value, db, w_id, user_db, authed).await?)), + None => Ok(None), + } +} + async fn resolve_provider_credentials( provider: &AIProvider, db: &DB, @@ -374,6 +404,41 @@ async fn resolve_provider_credentials( } else { None }; + let workload_identity_provider = resolve_optional_var( + resource.workload_identity_provider, + db, + w_id, + user_db.as_ref(), + authed, + ) + .await?; + let service_account_email = resolve_optional_var( + resource.service_account_email, + db, + w_id, + user_db.as_ref(), + authed, + ) + .await?; + let workload_identity_audience = resolve_optional_var( + resource.workload_identity_audience, + db, + w_id, + user_db.as_ref(), + authed, + ) + .await?; + let vertex_workload_identity = VertexWorkloadIdentity::from_resource( + provider, + workload_identity_provider.as_deref(), + service_account_email.as_deref(), + workload_identity_audience.as_deref(), + )?; + let platform = if vertex_workload_identity.is_some() { + AIPlatform::GoogleVertexAi + } else { + resource.platform + }; Ok(ProviderCredentials { provider: provider.clone(), @@ -388,7 +453,8 @@ async fn resolve_provider_credentials( aws_session_token, oidc_role_arn, anthropic_federation: None, - platform: resource.platform, + vertex_workload_identity, + platform, custom_headers: resource.headers, }) } @@ -427,6 +493,7 @@ async fn resolve_provider_credentials( service_account_id: resource.service_account_id, workspace_id: resource.workspace_id, }), + vertex_workload_identity: None, platform: AIPlatform::Standard, custom_headers: HashMap::new(), }) @@ -453,6 +520,7 @@ async fn resolve_provider_credentials( aws_session_token: None, oidc_role_arn: None, anthropic_federation: None, + vertex_workload_identity: None, platform: AIPlatform::Standard, custom_headers: HashMap::new(), }) @@ -672,17 +740,291 @@ async fn mint_anthropic_oidc_token(db: &DB, w_id: &str, authed: &ApiAuthed) -> R } } +/// Exchange an OIDC token minted for the requesting user for a Google access +/// token, sent as the Vertex bearer token, when the resource authenticates through +/// Workload Identity Federation. Runs after the workspace credential cache for the +/// same reason the Anthropic exchange does: the token names the user. +async fn resolve_vertex_workload_identity_credentials( + db: &DB, + w_id: &str, + authed: &ApiAuthed, + credentials: &mut ProviderCredentials, +) -> Result<()> { + let Some(identity) = credentials.vertex_workload_identity.as_ref() else { + return Ok(()); + }; + check_vertex_base_url(&credentials.base_url)?; + + let cache_key = (w_id.to_string(), identity.clone(), authed.email.clone()); + let token = match VERTEX_WORKLOAD_IDENTITY_TOKEN_CACHE + .get(&cache_key) + .filter(GcpAccessToken::is_fresh) + { + Some(cached) => cached, + None => { + let subject_token = + mint_vertex_oidc_token(db, w_id, authed, &identity.oidc_audience()).await?; + let token = exchange_oidc_token(identity, &subject_token).await?; + VERTEX_WORKLOAD_IDENTITY_TOKEN_CACHE.insert(cache_key, token.clone()); + token + } + }; + + credentials.api_key = Some(token.access_token); + Ok(()) +} + +async fn mint_vertex_oidc_token( + db: &DB, + w_id: &str, + authed: &ApiAuthed, + audience: &str, +) -> Result { + #[cfg(all(feature = "enterprise", feature = "openidconnect", feature = "private"))] + { + use windmill_ai::vertex_workload_identity::VERTEX_OIDC_TOKEN_LIFETIME_SECS; + use windmill_common::oidc_oss::{generate_id_token, OidcCaller, WorkspaceClaim}; + + let id_token = generate_id_token( + OidcCaller::GoogleVertex, + Some(db), + WorkspaceClaim { workspace: w_id.to_string() }, + audience, + format!("{}::{}", authed.email, w_id), + Some(authed.email.clone()), + Some(VERTEX_OIDC_TOKEN_LIFETIME_SECS), + ) + .await?; + Ok(id_token.to_string()) + } + #[cfg(not(all(feature = "enterprise", feature = "openidconnect", feature = "private")))] + { + let _ = (db, w_id, authed, audience); + Err(Error::BadRequest( + "Vertex AI Workload Identity Federation through Windmill's OIDC provider requires an enterprise license" + .to_string(), + )) + } +} + #[derive(Clone, Debug)] pub struct ExpiringProviderCredentials { credentials: ProviderCredentials, + policy: ModelPolicy, expires_at: std::time::Instant, instance_ai_config_revision: Option, } +/// The models a request served with the effective AI config's own key may ask one provider +/// for, and the output limit each is held to. The UI only offers what the settings enable; +/// this holds a direct API caller to it. +#[derive(Clone, Debug, Default)] +pub struct ModelPolicy { + models: std::collections::HashSet, + max_tokens: HashMap, +} + +/// The fields of a proxied body that [`ModelPolicy::check_body`] reads. +#[derive(Deserialize)] +struct ProxiedModel { + model: String, + models: Option>, + fallbacks: Option>, +} + +impl ModelPolicy { + fn new(config: &AIConfig, provider: &AIProvider) -> Self { + let enabled = config + .providers + .as_ref() + .and_then(|providers| providers.get(provider)) + .into_iter() + .flat_map(|p| p.models.iter()); + // Settings allow picking these without enabling them in the provider's list. + let picked = [ + &config.default_model, + &config.metadata_model, + &config.code_completion_model, + ] + .into_iter() + .flatten() + .filter(|m| &m.provider == provider) + .map(|m| &m.model); + // The browser sends a legacy `x/thinking` entry as `x`. + let models = enabled + .chain(picked) + .map(|m| m.strip_suffix("/thinking").unwrap_or(m).to_string()) + .collect(); + let prefix = format!( + "{}:", + serde_json::to_string(provider) + .unwrap_or_default() + .trim_matches('"') + ); + let max_tokens = config + .max_tokens_per_model + .iter() + .flatten() + .filter_map(|(key, limit)| { + Some((key.strip_prefix(&prefix)?.to_string(), i64::from(*limit))) + }) + .collect(); + Self { models, max_tokens } + } + + /// The output limit to send `model` with: `requested` capped at the configured limit, or + /// the limit itself when none was requested. Below 1 counts as none, since `-1` or `0` + /// mean "no limit" on servers such as Ollama. A model with no limit keeps `requested`. + fn output_tokens(&self, model: &str, requested: Option) -> Option { + let Some(&limit) = self.max_tokens.get(model) else { + return requested; + }; + Some( + requested + .filter(|n| *n >= 1) + .map_or(limit, |n| n.min(limit)), + ) + } + + /// Writes the configured limit into a body [`Self::check_body`] accepted for `model`. A + /// model with no limit keeps its body byte for byte. + fn limit_body( + &self, + model: &str, + provider: &AIProvider, + platform: &AIPlatform, + ai_path: &str, + body: &Bytes, + ) -> Result { + if !self.max_tokens.contains_key(model) { + return Ok(body.clone()); + } + let mut value: serde_json::Value = serde_json::from_slice(body) + .map_err(|e| Error::BadRequest(format!("invalid AI request body: {e}")))?; + let Some(obj) = value.as_object_mut() else { + return Ok(body.clone()); + }; + // The limit holds per choice, so several choices would multiply it. Legacy completions + // answer each prompt of a list; a flat list of tokens is one prompt. + let batched = obj + .get("prompt") + .and_then(|p| p.as_array()) + .is_some_and(|a| a.len() > 1 && !a.iter().all(|v| v.is_number())); + if batched + || ["n", "best_of"].iter().any(|k| { + obj.get(*k) + .is_some_and(|v| !v.is_null() && v.as_u64() != Some(1)) + }) + { + return Err(Error::BadRequest( + "only one prompt and one choice per request are supported with the workspace's AI key" + .to_string(), + )); + } + // Bedrock and Anthropic on Vertex generate for any POST, whatever its path; FIM is + // matched as its conversion matches it. A path that neither generates nor counts is + // refused rather than forwarded without the limit. + let path = ai_path.trim_end_matches('/'); + let fim = path.contains("fim/completions"); + let any_post_generates = *provider == AIProvider::AWSBedrock + || *provider == AIProvider::Anthropic && *platform == AIPlatform::GoogleVertexAi; + let generates = any_post_generates + || fim + || ["completions", "responses", "messages"] + .iter() + .any(|p| path.ends_with(p)); + if !generates { + if ["count_tokens", "input_tokens", "embeddings"] + .iter() + .any(|p| path.ends_with(p)) + { + return Ok(body.clone()); + } + return Err(Error::BadRequest(format!( + "\"{ai_path}\" can't be held to the token limit set for \"{model}\"" + ))); + } + // A caller's `max_tokens` stays where it is: any provider's base URL may point at a + // server that reads only `max_tokens` (Ollama), and the browser sends it there. + let field = if any_post_generates + || fim + || path.ends_with("messages") + || *provider == AIProvider::GoogleAI + { + "max_tokens" + } else if path.ends_with("responses") { + "max_output_tokens" + } else if path.ends_with("chat/completions") + && reads_max_completion_tokens(provider) + && !obj.contains_key("max_tokens") + { + "max_completion_tokens" + } else { + "max_tokens" + }; + // The smallest asked for that `output_tokens` counts as a request. + let requested = ["max_tokens", "max_completion_tokens", "max_output_tokens"] + .iter() + .filter_map(|f| obj.remove(*f)?.as_i64()) + .filter(|n| *n >= 1) + .min(); + obj.insert( + field.to_string(), + self.output_tokens(model, requested).into(), + ); + Ok(Bytes::from(serde_json::to_vec(&value).map_err(to_anyhow)?)) + } + + fn check_model(&self, model: &str) -> Result<()> { + if self.models.contains(model) { + Ok(()) + } else { + Err(Error::BadRequest(format!( + "model \"{model}\" is not enabled for this workspace" + ))) + } + } + + /// A body-less GET (a model listing) passes; any other request must be a JSON object + /// naming an enabled model, which is returned. + fn check_body(&self, method: &Method, body: &Bytes) -> Result> { + if method == Method::GET && body.is_empty() { + return Ok(None); + } + let invalid = |e: String| { + Error::BadRequest(format!( + "with the workspace's AI key, the request body must be a JSON object with a string \"model\": {e}" + )) + }; + // A struct also deserializes from a positional array, which the limit can't be written into. + if !body.trim_ascii_start().starts_with(b"{") { + return Err(invalid("not an object".to_string())); + } + let parsed: ProxiedModel = + serde_json::from_slice(body).map_err(|e| invalid(e.to_string()))?; + // Gateways fall back to the models listed here (OpenRouter `models`, LiteLLM + // `fallbacks`), which would run unchecked. + for (field, value) in [("models", &parsed.models), ("fallbacks", &parsed.fallbacks)] { + if value.is_some() { + return Err(Error::BadRequest(format!( + "\"{field}\" (fallback models) is not supported with the workspace's AI key" + ))); + } + } + self.check_model(&parsed.model)?; + Ok(Some(parsed.model)) + } +} + impl ExpiringProviderCredentials { - fn new(credentials: ProviderCredentials, instance_ai_config_revision: Option) -> Self { + fn new( + credentials: ProviderCredentials, + policy: ModelPolicy, + instance_ai_config_revision: Option, + ) -> Self { Self { credentials, + policy, expires_at: std::time::Instant::now() + std::time::Duration::from_secs(60), instance_ai_config_revision, } @@ -887,16 +1229,17 @@ async fn configured_credentials( db: &DB, w_id: &str, provider: &AIProvider, -) -> Result> { +) -> Result> { let cache_key = (w_id.to_string(), provider.clone()); if let Some(cached) = AI_REQUEST_CACHE.get(&cache_key).filter(|c| !c.is_expired()) { - return Ok(Some(cached.credentials)); + return Ok(Some((cached.credentials, cached.policy))); } let Some((mut ai_config, resource_workspace, instance_ai_config_revision)) = effective_ai_config(db, w_id).await? else { return Ok(None); }; + let policy = ModelPolicy::new(&ai_config, provider); let provider_config = ai_config .providers .as_mut() @@ -920,9 +1263,13 @@ async fn configured_credentials( resolve_provider_credentials(provider, db, &resource_workspace, resource, None).await?; AI_REQUEST_CACHE.insert( cache_key, - ExpiringProviderCredentials::new(credentials.clone(), instance_ai_config_revision), + ExpiringProviderCredentials::new( + credentials.clone(), + policy.clone(), + instance_ai_config_revision, + ), ); - Ok(Some(credentials)) + Ok(Some((credentials, policy))) } fn parse_ai_resource( @@ -1489,7 +1836,7 @@ async fn complete( ) -> JsonResult { let not_configured = || Error::BadRequest("AI is not configured for this workspace".to_string()); - let model = match request.model { + let mut model = match request.model { Some(model) => model, None => effective_ai_config(&db, &w_id) .await? @@ -1502,18 +1849,26 @@ async fn complete( ) })?, }; + if let Some(base) = model.model.strip_suffix("/thinking") { + model.model = base.to_string(); + } if model.provider.is_decision_provider() { return Err(Error::BadRequest(format!( "{:?} serves decision models, which answer typed questions rather than messages", model.provider ))); } - let mut credentials = configured_credentials(&db, &w_id, &model.provider) + let (mut credentials, policy) = configured_credentials(&db, &w_id, &model.provider) .await? .ok_or_else(not_configured)?; + policy.check_model(&model.model)?; + let max_tokens = policy + .output_tokens(&model.model, request.max_tokens.map(i64::from)) + .map(|n| u32::try_from(n).unwrap_or(u32::MAX)); #[cfg(feature = "bedrock")] resolve_bedrock_oidc_credentials(&db, &w_id, &authed, &mut credentials).await?; resolve_anthropic_federated_credentials(&db, &w_id, &authed, &mut credentials).await?; + resolve_vertex_workload_identity_credentials(&db, &w_id, &authed, &mut credentials).await?; // The query builders send the api key; only a federated Anthropic token has a way in. if credentials.access_token.is_some() && credentials.anthropic_federation.is_none() { return Err(Error::BadRequest(format!( @@ -1560,7 +1915,7 @@ async fn complete( query_builder: query_builder.as_ref(), credentials: &credentials, model: &model.model, - max_tokens: request.max_tokens, + max_tokens, reasoning_effort: None, timeout: Duration::from_secs(*AI_TIMEOUT_SECS), client: &client, @@ -1624,6 +1979,7 @@ async fn global_proxy( aws_session_token: None, oidc_role_arn: None, anthropic_federation: None, + vertex_workload_identity: None, platform: AIPlatform::Standard, custom_headers: HashMap::new(), }; @@ -1730,6 +2086,8 @@ async fn proxy( // Set when serving the request through Windmill's free AI tier (the lent key). Holds // the per-user concurrency lock and drives response metering. let mut free_lease: Option = None; + // Set when serving a request that names a model with the effective AI config's own key. + let mut policy: Option<(ModelPolicy, String)> = None; // An unsaved resource value (percent-encoded JSON), so a resource can be tested // before it is stored. `$var:` references resolve as the caller, and since the // caller also picks the base URL they are sent to, a scoped token needs the same @@ -1786,7 +2144,12 @@ async fn proxy( ) .await?; } - if let Some(credentials) = configured_credentials(&db, &w_id, &provider).await? { + if let Some((credentials, configured)) = + configured_credentials(&db, &w_id, &provider).await? + { + policy = configured + .check_body(&method, &body)? + .map(|model| (configured, model)); break 'cred credentials; } // Nothing configured: fall back to Windmill's free AI tier (EE-only) if a lent @@ -1814,12 +2177,16 @@ async fn proxy( #[cfg(feature = "bedrock")] resolve_bedrock_oidc_credentials(&db, &w_id, &authed, &mut credentials).await?; resolve_anthropic_federated_credentials(&db, &w_id, &authed, &mut credentials).await?; + resolve_vertex_workload_identity_credentials(&db, &w_id, &authed, &mut credentials).await?; // Free tier: pin the model and clamp max_tokens server-side before forwarding, // since the request body is otherwise client-controlled. if free_lease.is_some() { body = crate::ai_free_tier_oss::enforce_free_tier_body(&body)?; } + if let Some((policy, model)) = &policy { + body = policy.limit_body(model, &provider, &credentials.platform, &ai_path, &body)?; + } if let Some(fim_transform) = maybe_transform_fim_request(&provider, &ai_path, &credentials.base_url, &body)? @@ -2023,6 +2390,7 @@ mod tests { aws_session_token: None, oidc_role_arn: None, anthropic_federation: None, + vertex_workload_identity: None, platform: AIPlatform::Standard, custom_headers: HashMap::new(), } @@ -2083,15 +2451,27 @@ mod tests { AI_REQUEST_CACHE.clear(); AI_REQUEST_CACHE.insert( ("workspace-a".to_string(), AIProvider::OpenAI), - ExpiringProviderCredentials::new(sample_provider_credentials(), None), + ExpiringProviderCredentials::new( + sample_provider_credentials(), + ModelPolicy::default(), + None, + ), ); AI_REQUEST_CACHE.insert( ("workspace-a".to_string(), AIProvider::Anthropic), - ExpiringProviderCredentials::new(sample_provider_credentials(), None), + ExpiringProviderCredentials::new( + sample_provider_credentials(), + ModelPolicy::default(), + None, + ), ); AI_REQUEST_CACHE.insert( ("workspace-b".to_string(), AIProvider::OpenAI), - ExpiringProviderCredentials::new(sample_provider_credentials(), None), + ExpiringProviderCredentials::new( + sample_provider_credentials(), + ModelPolicy::default(), + None, + ), ); #[cfg(feature = "bedrock")] let assumed_role_key = { @@ -2127,6 +2507,285 @@ mod tests { assert!(BEDROCK_ASSUMED_ROLE_CACHE.get(&assumed_role_key).is_none()); } + #[test] + fn configured_key_serves_only_enabled_models() { + let config: AIConfig = serde_json::from_value(serde_json::json!({ + "providers": { + "openai": {"resource_path": "r", "models": ["gpt-4o"]}, + "anthropic": {"resource_path": "r", "models": ["claude-x"]} + }, + "default_model": {"provider": "openai", "model": "picked/thinking"} + })) + .unwrap(); + let policy = ModelPolicy::new(&config, &AIProvider::OpenAI); + let check = |body: serde_json::Value| { + policy.check_body(&Method::POST, &Bytes::from(body.to_string())) + }; + + let refused = check(serde_json::json!({"model": "claude-x"})).unwrap_err(); + assert!(refused.to_string().contains("\"claude-x\" is not enabled")); + assert!(check(serde_json::json!({"model": "picked"})).is_ok()); + assert!(policy.check_body(&Method::GET, &Bytes::new()).is_ok()); + assert!(policy.check_body(&Method::POST, &Bytes::new()).is_err()); + assert!(check(serde_json::json!({"model": "gpt-4o", "models": ["other"]})).is_err()); + assert!(check(serde_json::json!({"model": "gpt-4o", "fallbacks": ["other"]})).is_err()); + assert!(check(serde_json::json!({"messages": []})).is_err()); + assert!(check(serde_json::json!(["gpt-4o", null, null])).is_err()); + assert!(policy + .check_body(&Method::POST, &Bytes::from_static(b"--boundary")) + .is_err()); + } + + #[test] + fn configured_key_holds_requests_to_token_limits() { + let config: AIConfig = serde_json::from_value(serde_json::json!({ + "providers": { + "openai": {"resource_path": "r", "models": ["gpt-4o", "gpt-5", "unlimited"]}, + "googleai": {"resource_path": "r", "models": ["gemini-x"]}, + "anthropic": {"resource_path": "r", "models": ["claude-x"]}, + "aws_bedrock": {"resource_path": "r", "models": ["bedrock-x"]}, + "azure_openai": {"resource_path": "r", "models": ["production"]}, + "azure_foundry": {"resource_path": "r", "models": ["mistral-x"]}, + "customai": {"resource_path": "r", "models": ["llama"]}, + "deepseek": {"resource_path": "r", "models": ["deepseek-chat"]} + }, + "max_tokens_per_model": { + "openai:gpt-4o": 4000, "openai:gpt-5": 4000, + "googleai:gemini-x": 4000, "anthropic:claude-x": 4000, + "aws_bedrock:bedrock-x": 4000, "azure_openai:production": 4000, + "azure_foundry:mistral-x": 4000, "customai:llama": 4000, + "deepseek:deepseek-chat": 4000 + } + })) + .unwrap(); + let run_on = + |provider: AIProvider, platform: AIPlatform, path: &str, body: serde_json::Value| { + let policy = ModelPolicy::new(&config, &provider); + let body = Bytes::from(body.to_string()); + let model = policy.check_body(&Method::POST, &body)?.unwrap(); + policy.limit_body(&model, &provider, &platform, path, &body) + }; + let run = |path: &str, body: serde_json::Value| { + run_on(AIProvider::OpenAI, AIPlatform::Standard, path, body) + }; + + // Only the field the upstream reads reaches it, at the lowest valid value asked for, capped. + let limits = |body: Bytes| { + serde_json::from_slice::>(&body) + .unwrap() + .into_iter() + .filter(|(k, _)| k.starts_with("max_")) + .collect::>() + }; + use serde_json::json; + use AIPlatform::{GoogleVertexAi as Vertex, Standard}; + for (provider, platform, path, model, asked, sent) in [ + ( + AIProvider::GoogleAI, + Standard, + "chat/completions", + "gemini-x", + json!({"max_completion_tokens": 10}), + json!({"max_tokens": 10}), + ), + ( + AIProvider::Anthropic, + Standard, + "messages", + "claude-x", + json!({"max_completion_tokens": 100000}), + json!({"max_tokens": 4000}), + ), + ( + AIProvider::OpenAI, + Standard, + "fim/completions", + "gpt-4o", + json!({"max_completion_tokens": 100000}), + json!({"max_tokens": 4000}), + ), + ( + AIProvider::OpenAI, + Standard, + "fim/completions/x", + "gpt-4o", + json!({}), + json!({"max_tokens": 4000}), + ), + ( + AIProvider::CustomAI, + Standard, + "chat/completions", + "llama", + json!({"max_tokens": 100000, "max_completion_tokens": 9000}), + json!({"max_tokens": 4000}), + ), + ( + AIProvider::CustomAI, + Standard, + "chat/completions", + "llama", + json!({}), + json!({"max_completion_tokens": 4000}), + ), + ( + AIProvider::AzureFoundry, + Standard, + "chat/completions", + "mistral-x", + json!({"max_completion_tokens": 100000}), + json!({"max_completion_tokens": 4000}), + ), + ( + AIProvider::DeepSeek, + Standard, + "chat/completions", + "deepseek-chat", + json!({"max_completion_tokens": 100000}), + json!({"max_tokens": 4000}), + ), + ( + AIProvider::OpenAI, + Standard, + "chat/completions", + "gpt-4o", + json!({"max_tokens": 100000, "max_completion_tokens": 10}), + json!({"max_tokens": 10}), + ), + ( + AIProvider::OpenAI, + Standard, + "chat/completions", + "gpt-4o", + json!({"max_tokens": -1, "max_output_tokens": 0}), + json!({"max_tokens": 4000}), + ), + ( + AIProvider::AzureOpenAI, + Standard, + "chat/completions", + "production", + json!({}), + json!({"max_completion_tokens": 4000}), + ), + ( + AIProvider::OpenAI, + Standard, + "responses", + "gpt-5", + json!({"max_tokens": 100000}), + json!({"max_output_tokens": 4000}), + ), + ( + AIProvider::OpenAI, + Standard, + "completions", + "gpt-4o", + json!({"max_tokens": 500}), + json!({"max_tokens": 500}), + ), + // Bedrock and Anthropic on Vertex generate for any POST, whatever its path. + ( + AIProvider::AWSBedrock, + Standard, + "responses", + "bedrock-x", + json!({"max_output_tokens": 100000}), + json!({"max_tokens": 4000}), + ), + ( + AIProvider::AWSBedrock, + Standard, + "x", + "bedrock-x", + json!({}), + json!({"max_tokens": 4000}), + ), + ( + AIProvider::Anthropic, + Vertex, + "messages/count_tokens", + "claude-x", + json!({}), + json!({"max_tokens": 4000}), + ), + ( + AIProvider::Anthropic, + Standard, + "messages/count_tokens", + "claude-x", + json!({}), + json!({}), + ), + ( + AIProvider::OpenAI, + Standard, + "embeddings", + "gpt-4o", + json!({}), + json!({}), + ), + ] { + let mut body = asked.clone(); + body["model"] = model.into(); + let out = run_on(provider.clone(), platform, path, body).unwrap(); + assert_eq!( + serde_json::Value::Object(limits(out)), + sent, + "{provider:?} {path} {asked}" + ); + } + + // A model with no limit is forwarded byte for byte. + let raw = Bytes::from_static(br#"{ "model": "unlimited", "max_tokens": 9 }"#); + let policy = ModelPolicy::new(&config, &AIProvider::OpenAI); + assert_eq!( + policy + .limit_body( + "unlimited", + &AIProvider::OpenAI, + &Standard, + "chat/completions", + &raw + ) + .unwrap(), + raw + ); + assert_eq!(policy.output_tokens("gpt-4o", Some(100000)), Some(4000)); + assert_eq!(policy.output_tokens("gpt-4o", None), Some(4000)); + assert_eq!(policy.output_tokens("unlimited", Some(9)), Some(9)); + assert_eq!(policy.output_tokens("unlimited", None), None); + assert_eq!(policy.output_tokens("unlimited", Some(0)), Some(0)); + for no_limit in [0, -1] { + assert_eq!(policy.output_tokens("gpt-4o", Some(no_limit)), Some(4000)); + } + + // Where the limit can't be placed, the request is refused rather than sent without it. + assert!(run_on( + AIProvider::Anthropic, + Standard, + "conversations", + json!({"model": "claude-x"}) + ) + .is_err()); + for many in [ + json!({"model": "gpt-4o", "n": 2}), + json!({"model": "gpt-4o", "best_of": 2}), + json!({"model": "gpt-4o", "prompt": ["a", "b"]}), + json!({"model": "gpt-4o", "prompt": [[1, 2], [3]]}), + ] { + assert!(run("completions", many).is_err()); + } + for one in [ + json!({"model": "gpt-4o", "n": 1}), + json!({"model": "gpt-4o", "prompt": "a"}), + json!({"model": "gpt-4o", "prompt": ["a"]}), + json!({"model": "gpt-4o", "prompt": [1, 2, 3]}), + ] { + assert!(run("completions", one).is_ok()); + } + } + #[test] fn instance_backed_cache_entries_expire_when_revision_changes() { let _guard = TEST_LOCK.lock().unwrap(); @@ -2134,6 +2793,7 @@ mod tests { let cached = ExpiringProviderCredentials::new( sample_provider_credentials(), + ModelPolicy::default(), Some(current_instance_ai_config_revision()), ); assert!(!cached.is_expired()); diff --git a/backend/windmill-api/src/ai_session_tools/ai_providers.rs b/backend/windmill-api/src/ai_session_tools/ai_providers.rs index 940f511dca..d3a27abc57 100644 --- a/backend/windmill-api/src/ai_session_tools/ai_providers.rs +++ b/backend/windmill-api/src/ai_session_tools/ai_providers.rs @@ -44,9 +44,12 @@ struct Models { /// The kinds that serve decision models only, which an AI agent step cannot run on. const DECISION_ONLY_KINDS: &[&str] = &["typesafe", "cloudflare"]; -/// The model of OpenAI's Decisions API, the one kind both step types run on. -const OPENAI_DECISION_MODEL: &str = "gpt-6-luna"; -const DECISION_PROVIDER_KINDS: &[&str] = &["typesafe", "cloudflare", "openai"]; +/// The kinds both step types run on, with the model and name of their Decisions API. +const CHAT_KIND_DECISION_MODELS: &[(&str, &str, &str)] = &[ + ("openai", "gpt-6-luna", "OpenAI's Decisions API"), + ("googleai", "gemini-decision-1", "Gemini's Decisions API"), +]; +const DECISION_PROVIDER_KINDS: &[&str] = &["typesafe", "cloudflare", "openai", "googleai"]; const MAX_PROMPTED_MODELS: usize = 25; const PROVIDER_SHAPE: &str = r#"{ "type": "static", "value": { "kind": "", "resource": "$res:", "model": "" } }"#; @@ -270,7 +273,7 @@ fn check_provider(value: Option<&Value>, catalog: &Catalog, step_type: &str) -> )); } if step_type == "aidecision" && !DECISION_PROVIDER_KINDS.contains(&kind) { - return blocking(format!("an AI decision step runs on a decision model: provider.kind must be \"typesafe\", \"cloudflare\" or \"openai\", not \"{kind}\"")); + return blocking(format!("an AI decision step runs on a decision model: provider.kind must be \"typesafe\", \"cloudflare\", \"openai\" or \"googleai\", not \"{kind}\"")); } if step_type != "aidecision" && DECISION_ONLY_KINDS.contains(&kind) { return blocking(format!("\"{kind}\" serves decision models, which answer typed questions rather than messages: use an \"aidecision\" step rather than an AI agent")); @@ -307,10 +310,16 @@ fn check_provider(value: Option<&Value>, catalog: &Catalog, step_type: &str) -> found.kind )); } - // An OpenAI resource lists its chat models, which says nothing about its decision model. - if step_type == "aidecision" && kind == "openai" { - return (model != OPENAI_DECISION_MODEL).then(|| Issue { - message: format!("model \"{model}\" is not the model OpenAI's Decisions API is known to serve, \"{OPENAI_DECISION_MODEL}\""), + // An OpenAI or Google AI resource lists its chat models, which says nothing about its + // decision model. + let decision_model = CHAT_KIND_DECISION_MODELS + .iter() + .find(|(k, _, _)| *k == kind); + if let (true, Some((_, decision_model, api))) = (step_type == "aidecision", decision_model) { + return (model != *decision_model).then(|| Issue { + message: format!( + "model \"{model}\" is not the model {api} is known to serve, \"{decision_model}\"" + ), blocking: false, settled: false, }); diff --git a/backend/windmill-api/src/ai_session_tools/data.rs b/backend/windmill-api/src/ai_session_tools/data.rs index 3f8bbff5e7..2ee2b94728 100644 --- a/backend/windmill-api/src/ai_session_tools/data.rs +++ b/backend/windmill-api/src/ai_session_tools/data.rs @@ -720,7 +720,8 @@ RIGHT JOIN pg_namespace nsp ON table_schema = nsp.nspname WHERE nsp.nspname NOT AND NOT starts_with(nsp.nspname, 'pg_') AND has_schema_privilege(nsp.oid, 'USAGE')"; const MYSQL_SCHEMA_QUERY: &str = "SELECT DATABASE() AS default_db_name, TABLE_SCHEMA, TABLE_NAME, DATA_TYPE, COLUMN_NAME, COLUMN_DEFAULT FROM information_schema.columns WHERE table_schema = DATABASE() OR table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys', '_vt');"; const SNOWFLAKE_SCHEMA_QUERY: &str = "select TABLE_SCHEMA, TABLE_NAME, DATA_TYPE, COLUMN_NAME, COLUMN_DEFAULT, IS_NULLABLE from information_schema.columns where table_schema != 'INFORMATION_SCHEMA'"; -const MSSQL_SCHEMA_QUERY: &str = "select TABLE_SCHEMA, TABLE_NAME, DATA_TYPE, COLUMN_NAME, COLUMN_DEFAULT from information_schema.columns where table_schema != 'sys'"; +// Uppercase: under a case-sensitive collation `information_schema.columns` does not resolve. +const MSSQL_SCHEMA_QUERY: &str = "select TABLE_SCHEMA, TABLE_NAME, DATA_TYPE, COLUMN_NAME, COLUMN_DEFAULT from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA != 'sys'"; const BIGQUERY_SCHEMA_SCRIPT: &str = r#"import { BigQuery } from '@google-cloud/bigquery@7.5.0'; export async function main(args: bigquery) { const bq = new BigQuery({ diff --git a/backend/windmill-api/src/ai_session_tools/gen/instructions.json b/backend/windmill-api/src/ai_session_tools/gen/instructions.json index 9917964627..ac806db6cb 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/instructions.json +++ b/backend/windmill-api/src/ai_session_tools/gen/instructions.json @@ -223,6 +223,62 @@ "duckdb": "workspace_settings", "bunnative": "workspace_settings", "dbt": "workspace_settings" + }, + "display": { + "": "display", + "python3": "display", + "deno": "display", + "go": "display", + "bash": "display", + "powershell": "display", + "postgresql": "display", + "mysql": "display", + "bigquery": "display", + "snowflake": "display", + "mssql": "display", + "oracledb": "display", + "graphql": "display", + "nativets": "display", + "bun": "display", + "php": "display", + "rust": "display", + "ansible": "display", + "csharp": "display", + "nu": "display", + "java": "display", + "ruby": "display", + "rlang": "display", + "duckdb": "display", + "bunnative": "display", + "dbt": "display" + }, + "code_mode": { + "": "code_mode", + "python3": "code_mode", + "deno": "code_mode", + "go": "code_mode", + "bash": "code_mode", + "powershell": "code_mode", + "postgresql": "code_mode", + "mysql": "code_mode", + "bigquery": "code_mode", + "snowflake": "code_mode", + "mssql": "code_mode", + "oracledb": "code_mode", + "graphql": "code_mode", + "nativets": "code_mode", + "bun": "code_mode", + "php": "code_mode", + "rust": "code_mode", + "ansible": "code_mode", + "csharp": "code_mode", + "nu": "code_mode", + "java": "code_mode", + "ruby": "code_mode", + "rlang": "code_mode", + "duckdb": "code_mode", + "bunnative": "code_mode", + "dbt": "code_mode" } }, "texts": { @@ -252,15 +308,17 @@ "script.duckdb": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (duckdb)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- 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\n- 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\n- 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\n- Libraries are installed automatically - do not show installation instructions\n- 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\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# DuckDB\n\nArguments are defined with comments and used with `$name` syntax:\n\n```sql\n-- $name (text) = default\n-- $age (integer)\nSELECT * FROM users WHERE name = $name AND age > $age;\n```\n\n## Ducklake Integration\n\nAttach Ducklake for data lake operations:\n\n```sql\n-- Main ducklake\nATTACH 'ducklake' AS dl;\n\n-- Named ducklake\nATTACH 'ducklake://my_lake' AS dl;\n\n-- Then query\nSELECT * FROM dl.schema.table;\n```\n\n## External Database Connections\n\nConnect to external databases using resources:\n\n```sql\nATTACH '$res:path/to/resource' AS db (TYPE postgres);\nSELECT * FROM db.schema.table;\n```\n\n## S3 File Operations\n\nRead files from S3 storage:\n\n```sql\n-- Default storage\nSELECT * FROM read_csv('s3:///path/to/file.csv');\n\n-- Named storage\nSELECT * FROM read_csv('s3://storage_name/path/to/file.csv');\n\n-- Parquet files\nSELECT * FROM read_parquet('s3:///path/to/file.parquet');\n\n-- JSON files\nSELECT * FROM read_json('s3:///path/to/file.json');\n```\n\n### Receiving an S3Object as a script parameter\n\nDeclare the arg with type `(s3object)`. Windmill renders an S3 file picker for it\nand binds the arg as the bare `s3://storage/key` URI, which DuckDB's reader\nfunctions consume directly:\n\n```sql\n-- $file (s3object)\nSELECT * FROM read_parquet($file);\n```\n\nWorks with any DuckDB reader: `read_csv($file)`, `read_json($file)`, etc.\n\n### Writing query results to S3\n\nDuckDB writes to S3 natively via `COPY ... TO`:\n\n```sql\nCOPY (SELECT * FROM users) TO 's3:///exports/users.parquet' (FORMAT PARQUET);\n```\n\nUse this instead of the `-- s3` streaming directive supported by the other SQL\ndialects — that directive is not available in DuckDB.\n", "script.bunnative": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (bunnative)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- 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\n- 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\n- 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\n- Libraries are installed automatically - do not show installation instructions\n- 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\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n\n\n# TypeScript (Bun Native)\n\nNative TypeScript execution. Native scripts are Bun scripts that run on the native worker — a lightweight V8 isolate that exposes `fetch` and the JavaScript standard library — and can be heavily parallelized. Every script MUST start with `//native` on its first line so Windmill routes it to the native worker; without it the exact same script runs on the regular Bun worker. You may import npm packages and other Windmill scripts (e.g. `./helper.ts`) — imports are resolved and bundled just like a regular Bun script — as long as everything (your code and its dependencies) relies only on `fetch` and the standard library. Libraries that need Node/Bun runtime APIs (filesystem, `node:*` modules, child processes, native addons) will not work on the native worker; use the regular `bun` language for those.\n\n## Structure\n\nExport a single **async** function called `main`:\n\n```typescript\n//native\nexport async function main(param1: string, param2: number) {\n // Your code here\n return { result: param1, count: param2 };\n}\n```\n\nDo not call the main function.\n\n## Resource Types\n\nOn Windmill, credentials and configuration are stored in resources and passed as parameters to main.\n\nUse the `RT` namespace for resource types:\n\n```typescript\n//native\nexport async function main(stripe: RT.Stripe) {\n // stripe contains API key and config from the resource\n}\n```\n\nOnly use resource types if you need them to satisfy the instructions. Always use the RT namespace.\n\n## Imports\n\n**The constraint is the runtime, not the import list.** You may import npm packages and relative Windmill scripts; they are resolved and bundled exactly like a regular Bun script. But the native worker only provides `fetch` and the JavaScript standard library, so any imported code must work using only those. Anything requiring Node/Bun built-ins (`node:fs`, `child_process`, the `Bun` API, native modules) belongs in a regular `bun` script instead. Use the globally available `fetch` for HTTP:\n\n```typescript\n//native\nexport async function main(url: string) {\n const response = await fetch(url);\n return await response.json();\n}\n```\n\n## Pure computation: `//no_network`\n\nA 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:\n\n```typescript\n//native\n//no_network\nexport async function main(items: { price: number; qty: number }[]) {\n return items.reduce((sum, i) => sum + i.price * i.qty, 0);\n}\n```\n\n## Windmill Client\n\n`windmill-client` works on the native worker (its calls go over `fetch`), so use it as the **preferred way to talk to Windmill** — reading resources/variables/states, running scripts and flows, and the S3 helpers below (`loadS3File`, `loadS3FileStream`, `writeS3File`, `S3Object`). It handles auth, the workspace, and the base URL for you. Reserve raw `fetch` for calling *external* HTTP APIs that aren't Windmill.\n\nThe full `windmill-client` API reference (every exported function and its signature) is included below — consult it for the exact method instead of hand-rolling a `fetch` against the Windmill API.\n\n## Preprocessor Scripts\n\nFor preprocessor scripts, the function should be named `preprocessor` and receives an `event` parameter:\n\n```typescript\n//native\ntype Event = {\n kind:\n | \"webhook\"\n | \"http\"\n | \"websocket\"\n | \"kafka\"\n | \"email\"\n | \"nats\"\n | \"postgres\"\n | \"sqs\"\n | \"mqtt\"\n | \"amqp\"\n | \"gcp\"\n | \"azure\";\n body: any;\n headers: Record;\n query: Record;\n};\n\nexport async function preprocessor(event: Event) {\n return {\n param1: event.body.field1,\n param2: event.query.id,\n };\n}\n```\n\n## S3 Object Operations\n\nWindmill provides built-in support for S3-compatible storage operations. The `wmill.S3Object` type covers both the `s3://storage/key` URI form (`s3:///key` for the workspace default storage) and the `{ s3, storage? }` record form — always use it instead of redefining your own.\n\n### Receiving an S3Object as a script parameter\n\n```typescript\n//native\nimport * as wmill from \"windmill-client\";\n\nexport async function main(file: wmill.S3Object) {\n const content = await wmill.loadS3File(file);\n // ...\n}\n```\n\n### S3 operations\n\n```typescript\n//native\nimport * as wmill from \"windmill-client\";\n\n// Load file content from S3\nconst content: Uint8Array = await wmill.loadS3File(s3object);\n\n// Load file as stream\nconst blob: Blob = await wmill.loadS3FileStream(s3object);\n\n// Write file to S3\nconst result: wmill.S3Object = await wmill.writeS3File(\n s3object, // Target path (or undefined to auto-generate)\n fileContent, // string or Blob\n s3ResourcePath // Optional: specific S3 resource to use\n);\n```\n\n\n# TypeScript SDK (windmill-client)\n\nImport: import * as wmill from 'windmill-client'\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe helpers below are the surface to prefer. For an endpoint none of them covers, import the\ngenerated service classes (JobService, ScriptService, ...) from 'windmill-client' — they are not\nlisted here but they do exist. What does not exist is a helper name you guessed at: if it is\nneither listed below nor a service method, do not call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`process.env.WM_END_USER_EMAIL || process.env.WM_EMAIL`. WM_END_USER_EMAIL is the app viewer when\nthe run was triggered from an app and empty otherwise (both variables are always defined), WM_EMAIL\nis the user the job is permissioned as. WM_USERNAME is the matching username.\n\nworkerHasInternalServer(): boolean\n\n/**\n * Initialize the Windmill client with authentication token and base URL\n * @param token - Authentication token (defaults to WM_TOKEN env variable)\n * @param baseUrl - API base URL (defaults to BASE_INTERNAL_URL or BASE_URL env variable)\n */\nsetClient(token?: string, baseUrl?: string): void\n\n/**\n * Create a client configuration from env variables\n * @returns client configuration\n */\ngetWorkspace(): string\n\n/**\n * Get a resource value by path\n * @param path path of the resource, default to internal state path\n * @param undefinedIfEmpty if the resource does not exist, return undefined instead of throwing an error\n * @returns resource value\n */\nasync getResource(path?: string, undefinedIfEmpty?: boolean): Promise\n\n/**\n * Get the true root job id\n * @param jobId job id to get the root job id from (default to current job)\n * @returns root job id\n */\nasync getRootJobId(jobId?: string): Promise\n\n/**\n * Run a script synchronously by its path and wait for the result\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByPath(path: string, args: Record | null = null, verbose: boolean = false, tag: string | null = null): Promise\n\n/**\n * Run a script synchronously by its hash and wait for the result\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByHash(hash_: string, args: Record | null = null, verbose: boolean = false, tag: string | null = null): Promise\n\n/**\n * Append a text to the result stream\n * @param text text to append to the result stream\n */\nappendToResultStream(text: string): void\n\n/**\n * Stream to the result stream\n * @param stream stream to stream to the result stream\n */\nasync streamResult(stream: AsyncIterable): Promise\n\n/**\n * Run a flow synchronously by its path and wait for the result\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Flow execution result\n */\nasync runFlow(path: string | null = null, args: Record | null = null, verbose: boolean = false, tag: string | null = null): Promise\n\n/**\n * Wait for a job to complete and return its result\n * @param jobId - ID of the job to wait for\n * @param verbose - Enable verbose logging\n * @returns Job result when completed\n */\nasync waitJob(jobId: string, verbose: boolean = false): Promise\n\n/**\n * Get the result of a completed job\n * @param jobId - ID of the completed job\n * @returns Job result\n */\nasync getResult(jobId: string): Promise\n\n/**\n * Get the result of a job if completed, or its current status\n * @param jobId - ID of the job\n * @returns Object with started, completed, success, and result properties\n */\nasync getResultMaybe(jobId: string): Promise\n\n/**\n * Cancel a queued or running job by ID.\n * @param jobId - UUID of the job to cancel\n * @param reason - Optional reason for cancellation\n * @returns Response message from the cancel endpoint\n */\nasync cancelJob(jobId: string, reason: string | undefined = undefined): Promise\n\n/**\n * Run a script asynchronously by its path\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByPathAsync(path: string, args: Record | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise\n\n/**\n * Run a script asynchronously by its hash\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByHashAsync(hash_: string, args: Record | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise\n\n/**\n * Run a flow asynchronously by its path\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds)\n * @param doNotTrackInParent - If false, tracks state in parent job (only use when fully awaiting the job)\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runFlowAsync(path: string | null, args: Record | null, scheduledInSeconds: number | null = null, // can only be set to false if this the job will be fully await and not concurrent with any other job // as otherwise the child flow and its own child will store their state in the parent job which will // lead to incorrectness and failures doNotTrackInParent: boolean = true, tag: string | null = null): Promise\n\n/**\n * Resolve a resource value in case the default value was picked because the input payload was undefined\n * @param obj resource value or path of the resource under the format `$res:path`\n * @returns resource value\n */\nasync resolveDefaultResource(obj: any): Promise\n\n/**\n * Get the state file path from environment variables\n * @returns State path string\n */\ngetStatePath(): string\n\n/**\n * Set a resource value by path\n * @param path path of the resource to set, default to state path\n * @param value new value of the resource to set\n * @param initializeToTypeIfNotExist if the resource does not exist, initialize it with this type\n */\nasync setResource(value: any, path?: string, initializeToTypeIfNotExist?: string): Promise\n\n/**\n * Set the state\n * @param state state to set\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync setState(state: any, path?: string): Promise\n\n/**\n * Set the progress\n * Progress cannot go back and limited to 0% to 99% range\n * @param percent Progress to set in %\n * @param jobId? Job to set progress for\n */\nasync setProgress(percent: number, jobId?: any): Promise\n\n/**\n * Get the progress\n * @param jobId? Job to get progress from\n * @returns Optional clamped between 0 and 100 progress value\n */\nasync getProgress(jobId?: any): Promise\n\n/**\n * Whether the worker running this job has received its shutdown signal.\n * A draining worker waits for its current job to finish before exiting, so a\n * long-running script can poll this and return early to let the worker be replaced.\n * @param jobId? Job to check, defaults to the current job\n */\nasync workerIsDraining(jobId?: string): Promise\n\n/**\n * Set a flow user state\n * @param key key of the state\n * @param value value of the state\n */\nasync setFlowUserState(key: string, value: any, errorIfNotPossible?: boolean): Promise\n\n/**\n * Get a flow user state\n * @param path path of the variable\n */\nasync getFlowUserState(key: string, errorIfNotPossible?: boolean): Promise\n\n/**\n * Get the state shared across executions\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync getState(path?: string): Promise\n\n/**\n * Get a variable by path\n * @param path path of the variable\n * @returns variable value\n */\nasync getVariable(path: string): Promise\n\n/**\n * Set a variable by path, create if not exist\n * @param path path of the variable\n * @param value value of the variable\n * @param isSecretIfNotExist if the variable does not exist, create it as secret or not (default: false)\n * @param descriptionIfNotExist if the variable does not exist, create it with this description (default: \"\")\n */\nasync setVariable(path: string, value: string, isSecretIfNotExist?: boolean, descriptionIfNotExist?: string): Promise\n\n/**\n * Build a PostgreSQL connection URL from a database resource\n * @param path - Path to the database resource\n * @returns PostgreSQL connection URL string\n */\nasync databaseUrlFromResource(path: string): Promise\n\nasync polarsConnectionSettings(s3_resource_path: string | undefined): Promise\n\nasync duckdbConnectionSettings(s3_resource_path: string | undefined): Promise\n\n/**\n * Get S3 client settings from a resource or workspace default\n * @param s3_resource_path - Path to S3 resource (uses workspace default if undefined)\n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n * @returns S3 client configuration settings\n */\nasync denoS3LightClientSettings(s3_resource_path: string | undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Load the content of a file stored in S3. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContent = await wmill.loadS3FileContent(inputFile)\n * // if the file is a raw text file, it can be decoded and printed directly:\n * const text = new TextDecoder().decode(fileContentStream)\n * console.log(text);\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3File(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Load the content of a file stored in S3 as a stream. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContentBlob = await wmill.loadS3FileStream(inputFile)\n * // if the content is plain text, the blob can be read directly:\n * console.log(await fileContentBlob.text());\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3FileStream(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Persist a file to the S3 bucket. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * const s3object = await writeS3File(s3Object, \"Hello Windmill!\")\n * const fileContentAsUtf8Str = (await s3object.toArray()).toString('utf-8')\n * console.log(fileContentAsUtf8Str)\n * ```\n * \n * @param workspace - Workspace to write to (defaults to the `WM_WORKSPACE` env var)\n */\nasync writeS3File(s3object: S3Object | undefined, fileContent: string | Blob, s3ResourcePath: string | undefined = undefined, contentType: string | undefined = undefined, contentDisposition: string | undefined = undefined, workspace: string | undefined = undefined): Promise\n\n/**\n * Permanently delete a file from S3 by key.\n * \n * ```typescript\n * await wmill.deleteS3File({ s3: \"path/to/file.txt\" })\n * ```\n * \n * @param s3object - S3 object identifying the file to delete (must have `s3` set)\n * @param workspace - Workspace to delete from (defaults to the `WM_WORKSPACE` env var)\n */\nasync deleteS3File(s3object: S3Object, workspace: string | undefined = undefined): Promise\n\n/**\n * Sign S3 objects to be used by anonymous users in public apps\n * @param s3objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 objects\n */\nasync signS3Objects(s3objects: S3Object[], { expirySecs }: { expirySecs?: number } = {}): Promise\n\n/**\n * Sign S3 object to be used by anonymous users in public apps\n * @param s3object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 object\n */\nasync signS3Object(s3object: S3Object, { expirySecs }: { expirySecs?: number } = {}): Promise\n\n/**\n * Generate a presigned public URL for an array of S3 objects.\n * If an S3 object is not signed yet, it will be signed first.\n * @param s3Objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns list of signed public URLs\n */\nasync getPresignedS3PublicUrls(s3Objects: S3Object[], { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise\n\n/**\n * Generate a presigned public URL for an S3 object. If the S3 object is not signed yet, it will be signed first.\n * @param s3Object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed public URL\n */\nasync getPresignedS3PublicUrl(s3Objects: S3Object, { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise\n\n/**\n * Get URLs needed for resuming a flow after this step\n * @param approver approver name\n * @param flowLevel if true, generate resume URLs for the parent flow instead of the specific step.\n * This allows pre-approvals that can be consumed by any later suspend step in the same flow.\n * @returns approval page UI URL, resume and cancel API URLs for resuming the flow\n */\nasync getResumeUrls(approver?: string, flowLevel?: boolean): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Get an OIDC jwt token for auth to external services (e.g: Vault, AWS) (ee only)\n * @param audience audience of the token\n * @param expiresIn Optional number of seconds until the token expires\n * @returns jwt token\n */\nasync getIdToken(audience: string, expiresIn?: number): Promise\n\n/**\n * Convert a base64-encoded string to Uint8Array\n * @param data - Base64-encoded string\n * @returns Decoded Uint8Array\n */\nbase64ToUint8Array(data: string): Uint8Array\n\n/**\n * Convert a Uint8Array to base64-encoded string\n * @param arrayBuffer - Uint8Array to encode\n * @returns Base64-encoded string\n */\nuint8ArrayToBase64(arrayBuffer: Uint8Array): string\n\n/**\n * Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Slack approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Slack approval request.\n * @param {string} options.slackResourcePath - The path to the Slack resource in Windmill.\n * @param {string} options.channelId - The Slack channel ID where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Slack approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * @param {string} [options.resumeButtonText] - Optional text for the resume button.\n * @param {string} [options.cancelButtonText] - Optional text for the cancel button.\n * \n * @returns {Promise} Resolves when the Slack approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getSlackApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveSlackApproval({\n * slackResourcePath: \"/u/alex/my_slack_resource\",\n * channelId: \"admins-slack-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * resumeButtonText: \"Resume\",\n * cancelButtonText: \"Cancel\",\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveSlackApproval({ slackResourcePath, channelId, message, approver, defaultArgsJson, dynamicEnumsJson, resumeButtonText, cancelButtonText, }: SlackApprovalOptions): Promise\n\n/**\n * Sends an interactive approval request via Teams, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Teams approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Teams approval request.\n * @param {string} options.teamName - The Teams team name where the approval request will be sent.\n * @param {string} options.channelName - The Teams channel name where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Teams approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * \n * @returns {Promise} Resolves when the Teams approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getTeamsApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveTeamsApproval({\n * teamName: \"admins-teams\",\n * channelName: \"admins-teams-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveTeamsApproval({ teamName, channelName, message, approver, defaultArgsJson, dynamicEnumsJson, }: TeamsApprovalOptions): Promise\n\nsetWorkflowCtx(ctx: WorkflowCtx | null): void\n\nasync sleep(seconds: number): Promise\n\n/**\n * Execute `fn` inline and checkpoint the result. On replay the cached value is\n * returned without re-executing `fn`.\n * \n * `fn`'s result is encoded as JSON and decoded back before it is returned, so\n * the round that runs the body sees the same types every replay sees: a `Date`\n * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape.\n * \n * Called from inside a task body, `fn` runs in place and nothing is\n * checkpointed: a task is a single job and is never replayed.\n */\nasync step(name: string, fn: () => T | Promise,): Promise>>\n\n/**\n * Create a task that dispatches to a separate Windmill script.\n * \n * @example\n * const extract = taskScript(\"f/data/extract\");\n * // inside workflow: await extract({ url: \"https://...\" })\n */\ntaskScript(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike\n\n/**\n * Create a task that dispatches to a separate Windmill flow.\n * \n * @example\n * const pipeline = taskFlow(\"f/etl/pipeline\");\n * // inside workflow: await pipeline({ input: data })\n */\ntaskFlow(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike\n\n/**\n * Mark an async function as a workflow-as-code entry point.\n * \n * The function must be **deterministic**: given the same inputs it must call\n * tasks in the same order on every replay. Branching on task results is fine\n * (results are replayed from checkpoint), but branching on external state\n * (current time, random values, external API calls) must use `step()` to\n * checkpoint the value so replays see the same result.\n */\nworkflow(fn: (...args: any[]) => Promise): void\n\n/**\n * Suspend the workflow and wait for an external approval.\n * \n * Pass `key` to name the step, then `getApprovalUrls(key)` yields the URLs that\n * resume exactly this approval — route them through your own channel. Without a\n * key the steps are named `approval`, `approval_2`, ...\n * \n * `skin: \"minimal\"` shows approvers only the request (form and approve/reject)\n * instead of the detailed page with the workflow's details. `description` is\n * shown above the form: a string, or a rich value such as `{ markdown: \"...\" }`.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * const { value, approver } = await waitForApproval({ key: \"manager\", timeout: 3600 });\n */\nwaitForApproval(options?: { timeout?: number; form?: object; selfApproval?: boolean; key?: string; skin?: \"detailed\" | \"minimal\"; description?: string | object; }): PromiseLike<{ value: any; approver: string; approved: boolean }>\n\n/**\n * Resume/cancel/approval-page URLs bound to one `waitForApproval` step.\n * \n * Unlike `getResumeUrls()`, which signs a random nonce, these address the very\n * `resume_job` record the step's built-in approval buttons use, so they are\n * stable across replays and safe to embed in a custom notification.\n * \n * `stepKey` must match the `key` given to `waitForApproval`. Keys must be unique\n * within a workflow; reusing one throws rather than silently renaming it. The URL\n * only resumes while that step is awaiting approval; used at any other moment it is\n * rejected rather than banking a row a different approval would consume. Send it\n * ahead of time — approvers just cannot act before the workflow reaches the step.\n * \n * `resume` and `cancel` are step-bound; `approvalPage` is not — it opens the job's\n * approval page, which acts on whichever approval is pending when it is used.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * await waitForApproval({ key: \"manager\" });\n */\nasync getApprovalUrls(stepKey: string = \"approval\", approver?: string): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Process items in parallel with optional concurrency control.\n * \n * Each item is processed by calling `fn(item)`, which should be a task().\n * Items are dispatched in batches of `concurrency` (default: all at once).\n * \n * @example\n * const process = task(async (item: string) => { ... });\n * const results = await parallel(items, process, { concurrency: 5 });\n */\nasync parallel(items: T[], fn: (item: T) => PromiseLike | R, options?: { concurrency?: number },): Promise\n\n/**\n * Commit Kafka offsets for a trigger with auto_commit disabled.\n * @param triggerPath - Path to the Kafka trigger (from event.wm_trigger.trigger_path)\n * @param topic - Kafka topic name (from event.topic)\n * @param partition - Partition number (from event.partition)\n * @param offset - Message offset to commit (from event.offset)\n */\nasync commitKafkaOffsets(triggerPath: string, topic: string, partition: number, offset: number,): Promise\n\n/**\n * Parse an S3 object from URI string or record format\n * @param s3Object - S3 object as URI string (`s3://storage/key`, `s3:///key`\n * for the default storage) or record. Any other string throws rather than\n * falling back to an auto-generated key: an auto key is requested by\n * omitting the object, and a fallback would silently misplace the upload\n * on any typo.\n * @returns S3 object record with storage and s3 key\n */\nparseS3Object(s3Object: S3Object): S3ObjectRecord\n\n/**\n * Create a SQL template function for PostgreSQL/datatable queries\n * @param name - Database/datatable name (default: \"main\")\n * @param opts.role - Connect as this data table role instead of the data table's default one.\n * Only meaningful on a data table under roles, and only for a role you are a tenant of.\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.datatable()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}::int\n * `.fetch()\n * @example\n * // Read through a restricted role\n * let sql = wmill.datatable(\"main\", { role: \"analytics\" })\n */\ndatatable(name: string = \"main\", opts?: DatatableOptions): DatatableSqlTemplateFunction\n\n/**\n * Create a SQL template function for DuckDB/ducklake queries\n * @param name - DuckDB database name, optionally with a schema as `name:schema` (default: \"main\")\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.ducklake()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}\n * `.fetch()\n * @example\n * // Target a specific schema within the ducklake\n * let sql = wmill.ducklake(\"my_lake:analytics\")\n */\nducklake(name: string = \"main\"): SqlTemplateFunction\n\n/**\n * Idempotently materialize `selectSql` into a ducklake table for one\n * partition (or the whole table when `partition` is omitted) — the client-side\n * equivalent of the `// materialize` engine.\n * With `uniqueKey` it upserts the slice (delete-by-key + insert); otherwise it\n * replaces it (whole table → `CREATE OR REPLACE`; partition → delete + insert).\n * Safe to re-run for the same partition (backfill / failure-recovery).\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.upsertPartition({ table, selectSql, partition }).execute()`.\n */\nupsertPartition(opts: DucklakeMaterializeOptions): SqlStatement\n\n/**\n * INSERT-only materialization (no dedup/replace) for append-only tables.\n * Re-running the same partition duplicates rows — use only for immutable\n * event-log sources.\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.appendPartition({ table, selectSql, partition }).execute()`.\n */\nappendPartition(opts: Omit,): SqlStatement\n", "script.dbt": "# Global draft script instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, or generate metadata.\n- A script draft is a workspace item: `{ type: 'script', path, summary?, language, value, isDraft }` where `value` is the source code string.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Preserve the current path/language when modifying unless the user asked to change them.\n- Use `edit_script` for small localized changes (provide `old_string`/`new_string`); use `write_script` for full rewrites.\n\n# Windmill script authoring reference (dbt)\n\n# Windmill Script Writing Guide\n\n## General Principles\n\n- 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\n- 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\n- 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\n- Libraries are installed automatically - do not show installation instructions\n- 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\n- Where the language has a Windmill client (`wmill`), use it to interact with the platform\n- A script's input schema may carry a top-level `prompt_for_ai` string: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that script, and keep it when you rewrite the schema\n\n## Return Values\n\n- A script can return any JSON-serializable value; a SQL script returns the rows its query produces\n- Return values become available to subsequent flow steps via `results.step_id`\n\n## Preprocessor Scripts\n\nPreprocessor scripts process raw trigger data from various sources (webhook, custom HTTP route, SQS, WebSocket, Kafka, NATS, MQTT, AMQP, Postgres, GCP Pub/Sub, Azure, or email) before passing it to the flow. This separates the trigger logic from the flow logic and keeps the auto-generated UI clean.\n\nA preprocessor is written in TypeScript or Python: its function is named `preprocessor` instead of `main`, and it receives a single parameter called `event` (the language section gives its type).\n\nThe returned object determines the parameter values passed to the flow.\ne.g., `{ b: 1, a: 2 }` calls the flow with `a = 2` and `b = 1`, assuming the flow has two inputs called `a` and `b`.\n", - "flow": "# Global draft flow instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Never invent a folder.\n- `write_flow` mirrors flow mode's `set_flow_json`: pass `path`, optional `summary`, optional `description`, required `modules`, and optional `schema`, `preprocessor_module`, `failure_module`, `groups`, and `notes`. `summary` and `description` are top-level flow metadata (not part of the compact value `patch_flow_json` edits); the flow-structure arguments are JSON strings, matching the tool schema descriptions. When overwriting an existing flow, top-level flow settings (see below) are preserved from the current flow — use `patch_flow_json` to change them.\n- `read_workspace_item` returns a compact flow `value` object with `modules`, `schema`, `preprocessor_module`, `failure_module`, `groups`, `notes`, and any top-level flow settings that are set.\n- 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`: same_worker, preserve_step_tags, concurrent_limit, concurrency_key, concurrency_time_window_s, on_concurrency_limit, debounce_delay_s, debounce_key, debounce_args_to_accumulate, max_total_debouncing_time, max_total_debounces_amount, skip_expr, cache_ttl, cache_ignore_s3_path, delete_after_secs, timeout, flow_env, priority, early_return, chat_input_enabled. For example, `chat_input_enabled: true` marks a flow as chat-style (flow-as-chat); keep it intact when restructuring such a flow.\n- `modules` contains normal sequential modules. Use top-level `preprocessor_module` and `failure_module` for special modules; do not put `preprocessor` or `failure` in `modules`.\n- Every module needs a stable unique `id` and a useful `summary` when the schema supports it.\n- Prefer path/script/flow modules when composing existing workspace logic. Use rawscript modules only when new inline code is needed.\n- When writing rawscript module code, call `get_instructions` with `subject: \"script\"` and the rawscript language first.\n\n## Groups and notes\n\n- 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`.\n- 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.\n\n## Compact view: how rawscript bodies surface in tool I/O\n\n- `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.\"` so inline script bodies don't bloat tool I/O. Schema, groups, notes, preprocessor_module and failure_module are all shown in this view.\n- Inline rawscript content is **not** part of the JSON `patch_flow_json` sees. Edits to inline bodies happen via dedicated tools:\n - `read_flow_module_code(path, module_id)` — returns the raw inline script content for one module.\n - `set_flow_module_code(path, module_id, code)` — overwrites that module's inline script content; saves to the draft.\n- Use `patch_flow_json` for *structural* edits: module ids, paths, input_transforms, branch arrangement, summaries, preprocessor/failure swaps, schema/groups/notes. Use `set_flow_module_code` for changes inside a specific rawscript body.\n- When **adding a new rawscript module** with `patch_flow_json`, set its `content` to the placeholder `\"inline_script.\"` (matching the compact view) — never real code — then **immediately fill the body** with `set_flow_module_code(path, module_id, code)`. The module is saved with an empty body until you do; the tool result lists the module ids still awaiting code. A placeholder that names anything other than the module's own id or an existing rawscript module is rejected.\n- `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.\n - When overwriting an **existing** flow, set `\"content\": \"inline_script.\"` 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.\n\n\n# Windmill flow authoring reference\n\n# Windmill Flow Building Guide\n\n## OpenFlow Schema\n\nThe OpenFlow schema (openflow.openapi.yaml) is the source of truth for flow structure. Refer to OPENFLOW_SCHEMA for the complete type definitions.\n\n## Reserved Module IDs\n\n- `failure` - Reserved for failure handler module\n- `preprocessor` - Reserved for preprocessor module\n- `Input` - Reserved for flow input reference\n\n## Hard Structural Rules\n\nThese are strict Windmill schema rules. Follow them exactly.\n\n- `value.modules` is only for normal sequential steps\n- `value.preprocessor_module` and `value.failure_module` are special top-level fields inside `value`, not entries in `value.modules`\n- If a flow needs a preprocessor, create `value.preprocessor_module` with `id: preprocessor`\n- If a flow needs a failure handler, create `value.failure_module` with `id: failure`\n- Do NOT create regular modules inside `value.modules` named `preprocessor` or `failure`\n- `preprocessor_module` and `failure_module` only support `script` or `rawscript`\n- `preprocessor_module` runs before normal modules and cannot reference `results.*`\n- `failure_module` can use the `error` object with `error.message`, `error.step_id`, `error.name`, and `error.stack`\n- A flow whose `failure_module` runs still ends as failed, unless the handler returns an object with `recover: true`: the flow then ends as a success. This also holds when the failing step is inside a loop, a branch or a subflow. `recover` never changes which steps run; whether a loop or branch carries on past a failure is still decided by its own settings (`skip_failures`, `continue_on_error`)\n\nCorrect shape:\n\n```yaml\nvalue:\n preprocessor_module:\n id: preprocessor\n value:\n type: rawscript\n ...\n failure_module:\n id: failure\n value:\n type: rawscript\n ...\n modules:\n - id: process_event\n value:\n type: rawscript\n ...\n```\n\nIncorrect shape:\n\n```yaml\nvalue:\n modules:\n - id: preprocessor\n ...\n - id: process_event\n ...\n - id: failure\n ...\n```\n\n## Module ID Rules\n\n- Must be unique across the entire flow\n- Use underscores, not spaces (e.g., `fetch_data` not `fetch data`)\n- Use descriptive names that reflect the step's purpose\n\n## AI Agent Modules\n\nAn `aiagent` module runs an LLM that can call tools. Each entry of `value.tools` is a module-shaped\nobject with an extra `value.tool_type`: `flowmodule` for a script or inline script tool (or a nested\nagent or AI decision), `mcp` for an MCP server tool, `websearch` for web search, `question` for a\nbuilt-in `ask_question` tool (the agent stops, without holding a worker, until someone answers from\nthe run page or the chat; optional `value.timeout` in seconds, default 1800). Set\n`requires_approval: true` on a `flowmodule` or `mcp` tool to have a person approve or reject each of\nits calls before it runs.\n\n```json\n{\n \"id\": \"support_agent\",\n \"summary\": \"AI agent for customer support\",\n \"value\": {\n \"type\": \"aiagent\",\n \"input_transforms\": {\n \"provider\": {\n \"type\": \"static\",\n \"value\": { \"kind\": \"openai\", \"resource\": \"$res:f/ai_providers/openai\", \"model\": \"gpt-4o\" }\n },\n \"output_type\": { \"type\": \"static\", \"value\": \"text\" },\n \"user_message\": { \"type\": \"javascript\", \"expr\": \"flow_input.query\" },\n \"system_prompt\": { \"type\": \"static\", \"value\": \"You are a helpful assistant.\" }\n },\n \"tools\": [\n {\n \"id\": \"search_docs\",\n \"summary\": \"search_documentation\",\n \"description\": \"Search the product documentation. Use it whenever the user asks how a feature works.\",\n \"value\": {\n \"tool_type\": \"flowmodule\",\n \"type\": \"rawscript\",\n \"language\": \"bun\",\n \"content\": \"export async function main(query: string) { return ['doc1', 'doc2']; }\",\n \"input_transforms\": { \"query\": { \"type\": \"ai\" } }\n }\n }\n ]\n }\n}\n```\n\n- A flow cannot be a tool: a run offered one fails with `Unsupported tool`. Wrap it in a script\n that runs the flow\n- Each argument of a tool is either the model's or fixed. `{ \"type\": \"ai\" }` (or no value) lets the\n model fill it; a static value, an empty string included, fixes it and hides it from the model. Fix\n what the model must not choose, such as a resource, a table name or a limit\n- `provider` is an object, not a bare resource string: `{ \"kind\": ,\n \"resource\": \"$res:\", \"model\": }`. Required unless the module links to a saved\n agent through `value.agent`. Static is right for a flow run from a form; a chat flow wires its\n fields to flow inputs instead — see below\n\n### Chat-Mode Flows\n\nA flow with `value.chat_input_enabled: true` is run from a chat instead of a form: the composer\nsends one message per turn and renders the conversation. It needs a required `user_message` string\ninput, read by the agent. Any other flow input the composer does not edit itself is asked for\nunder Configure inputs.\n\n**A static `provider` gives a chat that cannot change its model.** Feed it from flow inputs\ninstead, either way round: one input carrying the whole object (`\"expr\": \"flow_input.model_config\"`)\nmakes every field editable, or wire it field by field to fix some and expose others. A field the\nchat can write becomes a control in the composer — a provider picker, a model list, a thinking\ncontrol — and a field left static is fixed, with no control drawn for it. `kind` is the one\nexception: the composer writes it only together with `resource`, since a provider is picked as a\npair, so a `kind` input wired on its own stays askable under Configure inputs and nothing the run\nneeds becomes unreachable.\n\n```json\n{\n \"id\": \"chat_agent\",\n \"value\": {\n \"type\": \"aiagent\",\n \"input_transforms\": {\n \"provider\": {\n \"type\": \"javascript\",\n \"expr\": \"({ kind: 'anthropic', resource: '$res:f/ai/claude', model: flow_input.model, reasoning_effort: flow_input.thinking })\"\n },\n \"user_message\": { \"type\": \"javascript\", \"expr\": \"flow_input.user_message\" },\n \"user_attachments\": { \"type\": \"javascript\", \"expr\": \"flow_input.files\" },\n \"memory\": { \"type\": \"static\", \"value\": { \"kind\": \"compaction\" } },\n \"streaming\": { \"type\": \"static\", \"value\": true },\n \"output_type\": { \"type\": \"static\", \"value\": \"text\" }\n },\n \"tools\": []\n }\n}\n```\n\n- Wiring field by field means one object literal whose values are literals or bare `flow_input.x`\n references. A spread, a call or a computed key leaves the composer unable to tell which input\n feeds which field, so it offers no control at all — a bare `flow_input.x` for the whole object\n is read instead as that one input carrying every field\n- A step linked to a saved agent (`agent` set) has no `provider` of its own. It exposes the same\n two controls through its `model` and `reasoning_effort` inputs, which replace what the agent\n saved: `\"model\": { \"type\": \"javascript\", \"expr\": \"flow_input.model\" }`. An empty model keeps the\n saved one, an empty effort sends none, and the provider resource always stays the agent's\n- `memory` is what lets the agent see earlier turns; without it every message starts from nothing\n- `streaming` on makes the answer and its thinking appear token by token instead of all at once\n- `user_attachments` points at a flow input typed as an array of s3 objects\n (`{ \"type\": \"array\", \"items\": { \"type\": \"object\", \"resourceType\": \"s3object\" } }`), so files\n sent with a message reach the agent\n- Running one needs a `memory_id` **query parameter** — not a flow argument — naming the\n conversation the turn belongs to: a fresh UUID starts one, reusing a UUID continues it. The chat\n supplies it itself; a run driven any other way has to pass it or the server refuses the job\n\n### Tool Naming Rules\n\nThese rules cover `flowmodule` tools, the ones the agent calls by name. A `websearch` or `question`\ntool's `summary` is a plain label (`Web Search`), and an `mcp` tool exposes the MCP\nserver's own tool names, so none is name-checked at all — leave those summaries as they are.\n\n- A flowmodule tool's `summary` is the **name the agent calls it by**, not a human label. Put the\n human-readable explanation in `description`\n- `summary` must match `^[a-zA-Z0-9_]+$`: letters, numbers and underscores only. No spaces, dashes,\n dots or accents — `search_documentation`, never `Search documentation`\n- Always set `summary`. It must be unique among that agent's tools, and must not be one of the\n reserved ids (`do`, `bg`, `ctx`, `state`, `if`, `else`, `for`, `delete`, `while`, `new`, `in`,\n `failure`, `preprocessor`, `as`, `Input`, `Result`, `Trigger`)\n- A tool name outside that character set fails any run that offers the tool to the agent, with `Invalid tool name`.\n The flow write tools refuse such a name.\n- Tool `id` follows the same rules as any module ID — unique across the flow, underscores not spaces\n- `description` is optional free text telling the agent when and how to call the tool. Set it\n whenever the name alone does not make that obvious; it overrides the description derived from the\n underlying script\n\n## AI Decision Modules\n\nAn `aidecision` module asks a decision model (TypeSafe's Jev, Cloudflare's Clef or OpenAI's Decisions API) typed questions about a `state` and\nanswers each with calibrated probabilities instead of text. Prefer it over an `aiagent` when the step\nis a judgment (classify, route, score or a yes/no check) that needs no tools and no free text: it\nis faster, cheaper, and its answers have a fixed shape.\n\n```json\n{\n \"id\": \"triage\",\n \"summary\": \"Classify the ticket\",\n \"value\": {\n \"type\": \"aidecision\",\n \"input_transforms\": {\n \"provider\": {\n \"type\": \"static\",\n \"value\": { \"kind\": \"typesafe\", \"resource\": \"$res:f/ai/typesafe\", \"model\": \"jev-latest\" }\n },\n \"state\": { \"type\": \"javascript\", \"expr\": \"flow_input.message\" },\n \"questions\": {\n \"type\": \"static\",\n \"value\": {\n \"intent\": {\n \"type\": \"choice\",\n \"instructions\": \"What does the customer want?\",\n \"criteria\": { \"refund\": \"Money back\", \"bug\": \"Something is broken\", \"other\": \"Anything else\" }\n },\n \"urgency\": {\n \"type\": \"score\",\n \"instructions\": \"How urgent is the ticket?\",\n \"criteria\": [\"Can wait\", \"This week\", \"Today\", \"Right now\"]\n },\n \"angry\": { \"type\": \"noul\", \"instructions\": \"Is the customer angry?\" }\n }\n }\n }\n }\n}\n```\n\n- `provider.kind` is `typesafe` (`model` `jev-latest` unless a version is pinned), `cloudflare`\n (`model` `clef`, or `clef-flash` for faster answers) or `openai` (`model` `gpt-6-luna`, never a\n chat model); the resource is of that same type\n- `state` is the content to evaluate: usually a text, such as the message to classify. To combine\n several values, pass an object with descriptive keys holding only what the questions need\n (`({ message: flow_input.message, plan: results.get_account.plan })`); an array of strings also works\n- `questions` maps each question name to `{ type, instructions, criteria }`:\n - `choice`: `criteria` maps each option to its description (up to 255 options). The answer has\n `choice`, `probabilities` and `confidence`\n - `score`: `criteria` is an ordered array of 2 to 10 level descriptions. The answer has `score`,\n `legend`, `probabilities` and `confidence`\n - `noul`: yes/no, `criteria` optionally `{ \"true\": ..., \"false\": ... }` descriptions. The answer has\n `noul`, the probability of yes from 0 to 1\n- The result is `{ output, model, usage }` with `output` keyed by question name, so a later step\n reads `results.triage.output.intent.choice`, `results.triage.output.urgency.score` or\n `results.triage.output.angry.noul > 0.7`\n- On `openai` the same `questions` are translated for its Decisions API and the answers read the\n same way (`choice`, `score`, `noul`), except that `probabilities` is a list of\n `{ value, probability }` (plus `label` on a score) and a score has no `legend`. A question OpenAI\n refuses to answer fails the step. A `state` that is\n an array of user messages (`[{ role: \"user\", content: [{ type: \"input_text\", text }, { type: \"input_image\", image_url: \"data:image/png;base64,...\" }] }]`)\n is sent as is, which is how an image is evaluated; any other object or array is sent as JSON text\n\n### Branching on the Answers\n\nTo route on the answers, put a `branchone` right after the decision, one branch per option, with\neach `expr` reading the decision by id:\n\n```json\n{\n \"id\": \"route\",\n \"value\": {\n \"type\": \"branchone\",\n \"branches\": [\n { \"summary\": \"refund\", \"expr\": \"results.triage.output.intent.choice === 'refund'\", \"modules\": [...] },\n { \"summary\": \"bug\", \"expr\": \"results.triage.output.intent.choice === 'bug'\", \"modules\": [...] }\n ],\n \"default\": [...]\n }\n}\n```\n\nFor a yes/no question, one branch with `\"expr\": \"results.triage.output.angry.noul >= 0.5\"` (tune the\nthreshold as needed) and the `default` as the \"no\" path.\n\n### As an Agent Tool\n\nAn `aidecision` can be a `flowmodule` tool of an `aiagent` (`\"tool_type\": \"flowmodule\", \"type\":\n\"aidecision\"`): set `state` to `{ \"type\": \"ai\" }` so the calling model supplies it, and only `output`\ngoes back to the model. The Tool Naming Rules apply to its `summary`. Only a flow's own agent step\ncan call one, not an agent used as a tool.\n\n## Common Mistakes to Avoid\n\n- Missing `input_transforms` - Rawscript parameters won't receive values without them\n- Referencing future steps - `results.step_id` only works for steps that execute before the current one\n- Duplicate module IDs - Each module ID must be unique in the flow\n- AI agent flowmodule tool names with spaces - `summary` is the tool name and only accepts letters, numbers and underscores\n\n## Data Flow Between Steps\n\n- `flow_input.property` - Access flow input parameters\n- `results.step_id` - Access output from a previous step only when that step result is in scope\n- `results.step_id.property` - Access specific property from a previous step output only when that step result is in scope\n- `flow_input.iter.value` - Current iteration value inside a `forloopflow`; in a `whileloopflow` it is just the iteration index (a plain number, same as `flow_input.iter.index`)\n- `flow_input.iter.index` - Current loop index when inside a loop (`forloopflow` or `whileloopflow`)\n- After a suspend step (approval), the next step's javascript expressions also get:\n - `resume` - the last resume payload (the resume form values); with `continue_on_disapprove_timeout`, a disapproval or timeout yields `{ error: { name: \"SuspendedDisapproved\" | \"SuspendedTimedOut\", message } }` instead, plus `reason` on a disapproval whose approver gave one\n - `resumes` - every resume payload, in arrival order\n - `approvers` - a plain array of strings, one per resume: for a resume through the `resume`/`cancel` URL from `getResumeUrls(approver)`, the `approver` passed there if any; otherwise (including the `approvalPage` link) the resuming user's username, else `\"anonymous\"`, e.g. `approvers[0]`. It is NOT the `{ resume_id, approver }` objects stored in the flow status, so `approvers[0].approver` is always undefined\n\n## Loop Structure Rules\n\n- A `forloopflow` runs its `modules` once per element of `iterator`, a javascript expression returning an array (e.g. `results.get_items`); `parallel: true` runs the iterations concurrently, and `skip_failures: true` carries on past a failed iteration\n- For `whileloopflow`, break the loop with a module-level `stop_after_if`: on the loop module itself, or on an inner step (required when that step carries state via its own `results` — see below)\n- `stop_after_if` is always a sibling of `id` and `value` on a flow module — never a direct key of the loop's `value` object\n- `stop_after_all_iters_if` is for checks after the whole loop finishes, not the normal per-iteration break condition\n- `stop_after_if` is evaluated after each iteration: on the loop module, `result` is that iteration's result (what its last step returned); on an inner step, it is that step's result\n- `flow_input.iter.value` in a `whileloopflow` is just the iteration index (same number as `flow_input.iter.index`) — it never carries state, so `flow_input.iter.value.` is always undefined and a loop whose stop condition depends on it never terminates\n- To carry state across iterations, a step reads its own previous-iteration result via `results.` with a first-iteration fallback (e.g. `results.b ?? flow_input.start`) — but then the loop's `stop_after_if` MUST sit on that inner step, not on the loop module: a body that is exactly one plain step with the stop condition on the loop module runs on a fast path where `results.` is null on every iteration and the loop never terminates (bodies with 2+ steps, or whose single step has its own `stop_after_if`, retry or similar, resolve `results` across iterations regardless of stop placement)\n- To cap a `whileloopflow`, set `max_iterations` and/or `max_duration_secs` (seconds since the first iteration started) on the loop's `value`, rather than encoding the bound into `stop_after_if`. Both are checked after each iteration, so a running iteration is never interrupted and the loop can exceed `max_duration_secs` by at most one iteration (bound an iteration with its steps' `timeout`); whichever is reached first, unless `stop_after_if` stopped the loop at that iteration, fails the loop with `{ error: { name: \"LoopExhausted\", message } }`. To handle it, set `continue_on_error: true` on the loop and branch in the next step on `results..error?.name === \"LoopExhausted\"` (only the step right after the loop sees the error there; later steps see the iterations' results); retries and the failure module apply as for any step failure. For a pause between iterations, set `sleep` on the body's step\n- For state that is just a counter, derive it from the index instead (e.g. `flow_input.iter.index + 1`) — that works in every configuration, including with `stop_after_if` on the loop module\n- If the user asks for a final scalar/object after a loop, add a normal step after the loop that extracts the final value from the loop result instead of returning the whole loop result array\n\nCorrect `whileloopflow` shape:\n\n```yaml\n- id: loop_until_done\n stop_after_if:\n expr: result.done === true\n skip_if_stopped: false\n value:\n type: whileloopflow\n skip_failures: false\n modules:\n - id: advance_state\n value:\n type: rawscript\n input_transforms:\n count:\n type: javascript\n expr: flow_input.iter.index + 1\n- id: return_final_state\n value:\n type: rawscript\n input_transforms:\n final_state:\n type: javascript\n expr: results.loop_until_done[results.loop_until_done.length - 1]\n```\n\nCorrect `whileloopflow` shape carrying state via `results` (stop condition on the inner step):\n\n```yaml\n- id: loop_until_done\n value:\n type: whileloopflow\n skip_failures: false\n modules:\n - id: advance_state\n stop_after_if:\n expr: result.done === true\n skip_if_stopped: false\n value:\n type: rawscript\n input_transforms:\n state:\n type: javascript\n expr: results.advance_state ?? flow_input.initial_state\n```\n\nIncorrect `whileloopflow` patterns:\n\n```yaml\n- id: loop_until_done\n value:\n type: whileloopflow\n stop_after_if:\n expr: result.done === true\n```\n\n```yaml\ninput_transforms:\n state:\n type: javascript\n # iter.value is a number (the iteration index); there is no previous-iteration state\n expr: flow_input.iter.value.count\n```\n\n```yaml\ninput_transforms:\n final_state:\n type: javascript\n expr: results.loop_until_done\n```\n\n## Approval / Suspend Structure\n\nAn approval step is a normal **script** step (`type: rawscript` or `type: script`) that is turned into an approval by adding a module-level `suspend`. Its script calls `wmill.getResumeUrls(approver)` to generate the secret resume/cancel URLs and returns them so they can be sent to the approver(s) (Slack, email, etc.) or approved from the run page.\n\n- `suspend` belongs on the flow module object itself, as a sibling of `id` and `value`\n- Never put `suspend` inside `value`\n- Do NOT use `type: identity` for an approval step. An identity step suspends but never produces the resume URLs, so approvers have no link to act on — it is not a functional approval.\n\nCorrect shape:\n\n```yaml\n- id: request_approval\n suspend:\n required_events: 1\n resume_form:\n schema:\n type: object\n properties:\n comment:\n type: string\n required: [comment]\n value:\n type: rawscript\n language: bun\n input_transforms:\n approver:\n type: static\n value: ''\n content: |\n import * as wmill from \"windmill-client\"\n\n export async function main(approver?: string) {\n const urls = await wmill.getResumeUrls(approver)\n // send urls.resume / urls.cancel to the approver(s), e.g. via Slack or email\n return urls\n }\n```\n\nIncorrect shape (suspend misplaced inside `value`):\n\n```yaml\n- id: request_approval\n value:\n type: rawscript\n suspend:\n required_events: 1\n```\n\nIncorrect shape (identity has no resume URLs — not a real approval):\n\n```yaml\n- id: request_approval\n suspend:\n required_events: 1\n value:\n type: identity\n```\n\n## Branch Result Scope Rules\n\n- A `branchone` runs the first of its `branches` whose `expr` is true, in order, and its `default` modules when none is; a `branchall` runs every branch (concurrently with `parallel: true`)\n- Inside a branch, you may reference earlier outer steps and earlier steps in the same branch\n- Outside a `branchone`, do NOT reference ids of steps that only exist inside its branches or default branch. Use `results.` instead\n- Outside a `branchall`, do NOT reference ids of steps inside its branches. Use `results.` instead\n- If downstream steps need a stable shape after a branch, make each branch return the same fields\n- When needed, add a normalization step immediately after the branch and consume `results.` there\n\nCorrect after `branchone`:\n\n```yaml\n- id: route_order\n value:\n type: branchone\n ...\n- id: send_confirmation\n value:\n input_transforms:\n routed:\n type: javascript\n expr: results.route_order\n```\n\nIncorrect after `branchone`:\n\n```yaml\nexpr: results.create_shipment\nexpr: results.create_backorder\n```\n\nCorrect after `branchall`:\n\n```yaml\n- id: enrich_parallel\n value:\n type: branchall\n parallel: true\n ...\n- id: combine_data\n value:\n input_transforms:\n enrichments:\n type: javascript\n expr: results.enrich_parallel\n```\n\n## Input Transforms\n\nEvery rawscript module needs `input_transforms` to map function parameters to values:\n\nStatic transform (fixed value):\n{\"param_name\": {\"type\": \"static\", \"value\": \"fixed_string\"}}\n\nJavaScript transform (dynamic expression):\n{\"param_name\": {\"type\": \"javascript\", \"expr\": \"results.previous_step.data\"}}\n\n## Resource References\n\n- For flow inputs: Use type `\"object\"` with format `\"resource-{type}\"` (e.g., `\"resource-postgresql\"`)\n- For step inputs: Use static value `\"$res:path/to/resource\"`\n\n## Reusing Existing Scripts and Flows\n\nUnless the user asked for new code, look for a workspace script or flow that already does a step's job before writing it, and reuse it by path instead of copying its logic into a rawscript:\n\n- a workspace script: `type: script` with `path` (e.g. `f/folder/send_email`)\n- a workspace flow, run as a subflow: `type: flow` with `path`\n- a Hub script: `type: script` with a `hub///` path\n\nThe step's `input_transforms` must cover the reused item's inputs, so read its input schema first.\n\n## Additional Prompt for AI\n\nA flow's input schema may carry a top-level `prompt_for_ai` string, as a script's can: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that flow, and keep it when you rewrite the schema.\n\n## Organizing Flows: Groups and Notes\n\nGroups and notes shape how a flow reads in the editor; neither changes what it does.\n\n**Segment every non-trivial flow into groups without waiting to be asked.** Whenever a flow has more than a couple of steps, or consecutive steps form a stage (\"fetch\", \"transform\", \"notify\"), put them in a group, and aim for every meaningful step to belong to one. Use notes sparingly, for flow-wide information that belongs to no span of steps: the flow's purpose, key assumptions, warnings, TODOs. One note is usually enough; never label a run of steps with a note, which is what a group is for.\n\n`value.groups` lists the groups, each spanning the steps from `start_id` to `end_id`:\n\n- `start_id`, `end_id` (required): ids of the group's first and last step; the same id for both makes a one-step group\n- `summary`: the group's title\n- `note`: markdown shown under the title\n- `color`: one of `yellow`, `blue`, `green`, `purple`, `pink`, `orange`, `red`, `cyan`, `lime`, `gray`, never a hex code or CSS color; leave it out and the editor picks one\n- `autocollapse`: `true` shows the group collapsed by default\n\nThe editor refuses to draw a flow whose groups break any of these rules:\n\n- `start_id` and `end_id` are steps of the same list: both top-level, or both in the same loop body or branch. A group can hold a loop or branch step whole, but cannot start outside one and end inside it\n- `start_id` does not come after `end_id` in that list\n- groups nest (one entirely inside another) but never partly overlap, and no two groups share both `start_id` and `end_id`\n- groups hold ordinary steps only: never `preprocessor`, `failure`, `Input`, `Result`, `Trigger`, or an AI agent's tools\n\n`value.notes` lists sticky notes, each with a unique `id`, markdown `text`, a `color` from the same list, and `type: free`. The `group` note type is deprecated; use `value.groups` instead.\nLeave a note's `position` and `size` out and they are filled in for you.\n\n## Final Structural Self-Check\n\nBefore finalizing a flow, verify:\n\n- any preprocessor is in `value.preprocessor_module`\n- any failure handler is in `value.failure_module`\n- any approval step has module-level `suspend`\n- no downstream step references inner branch step ids from outside the branch\n- every AI agent flowmodule tool has a unique `summary` made only of letters, numbers and underscores\n- every group starts and ends on steps of the same list, start before end, nesting without partial overlap\n\n## S3 Object Operations\n\nWindmill provides built-in support for S3-compatible storage operations.\n\nTo accept an S3 object as flow input:\n\n```json\n{\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\n \"type\": \"object\",\n \"format\": \"resource-s3_object\",\n \"description\": \"File to process\"\n }\n }\n}\n```\n\n## Using Resources in Flows\n\nOn Windmill, credentials and configuration are stored in resources. Resource types define the format of the resource.\n\n### As Flow Input\n\nIn the flow schema, set the property type to `\"object\"` with format `\"resource-{type}\"`:\n\n```json\n{\n \"type\": \"object\",\n \"properties\": {\n \"database\": {\n \"type\": \"object\",\n \"format\": \"resource-postgresql\",\n \"description\": \"Database connection\"\n }\n }\n}\n```\n\n### When No Resource Type Fits\n\nA 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.\n\n- 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.\n- Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it.\n- A plain variable is fine when the user asks for it.\n\n### As Step Input (Static Reference)\n\nReference a specific resource using `$res:` prefix:\n\n```json\n{\n \"database\": {\n \"type\": \"static\",\n \"value\": \"$res:f/folder/my_database\"\n }\n}\n```\n\n\n## OpenFlow Schema\n\n{\"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\"},\"on_concurrency_limit\":{\"type\":\"string\",\"enum\":[\"queue\",\"fail\"],\"description\":\"What a run of this flow does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed, like any failed step.\"},\"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\"},\"timeout\":{\"type\":\"integer\",\"description\":\"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error.\"},\"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 after this step completes, before the next step starts (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\"},\"preview_only\":{\"type\":\"boolean\",\"description\":\"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.\"}}},\"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\"},\"on_concurrency_limit\":{\"type\":\"string\",\"enum\":[\"queue\",\"fail\"],\"description\":\"What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed.\"},\"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\"},\"max_iterations\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'\"},\"max_duration_secs\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'\"}},\"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\"},\"parallelism\":{\"description\":\"Maximum number of branches running at once when parallel=true. Can be static number or expression\",\"$ref\":\"#/components/schemas/InputTransform\"}},\"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, websearch or question 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.\"},\"requires_approval\":{\"type\":\"boolean\",\"description\":\"Flowmodule and mcp tools only. Each call waits for a person to approve or reject it from the flow's run page or chat, without the agent holding a worker. Calls in the same turn that do not require approval run right away. A rejected call, or one nobody answers within 30 minutes, is reported to the AI as not run.\"},\"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\"},{\"$ref\":\"#/components/schemas/QuestionToolValue\"}],\"discriminator\":{\"propertyName\":\"tool_type\",\"mapping\":{\"flowmodule\":\"#/components/schemas/FlowModuleTool\",\"mcp\":\"#/components/schemas/McpToolValue\",\"websearch\":\"#/components/schemas/WebsearchToolValue\",\"question\":\"#/components/schemas/QuestionToolValue\"}}},\"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\"]},\"QuestionToolValue\":{\"type\":\"object\",\"description\":\"Built-in tool the AI calls as ask_question: the agent stops, releasing its worker, until someone answers from the flow's run page or chat or the question times out, then resumes with the answer as the tool result.\",\"properties\":{\"tool_type\":{\"type\":\"string\",\"enum\":[\"question\"]},\"timeout\":{\"type\":\"integer\",\"description\":\"Seconds to wait for an answer before the question is reported to the AI as timed out. Defaults to 1800.\"}},\"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\":[\"approval\"]},\"call_id\":{\"type\":\"string\"},\"calls\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"function_name\":{\"type\":\"string\"},\"arguments\":{}},\"required\":[\"function_name\",\"arguments\"]}},\"expires_at\":{\"type\":\"string\",\"format\":\"date-time\"}},\"required\":[\"type\",\"call_id\",\"calls\",\"expires_at\"]},{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"question\"]},\"call_id\":{\"type\":\"string\"},\"question\":{\"type\":\"string\"},\"choices\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"answers the model proposes; a free-text answer is always possible\"},\"multi_select\":{\"type\":\"boolean\",\"description\":\"whether several choices can be picked together\"},\"expires_at\":{\"type\":\"string\",\"format\":\"date-time\"}},\"required\":[\"type\",\"call_id\",\"question\",\"expires_at\"]},{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"message\"]}},\"required\":[\"content\",\"type\"]}]}},\"agent_actions_success\":{\"type\":\"array\",\"items\":{\"type\":\"boolean\"}}},\"required\":[\"type\"]}}", + "flow": "# Global draft flow instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata.\n- Paths follow the conventions in the system prompt: default to `u//` when the user gave a bare name; only use `f//` when the folder is known to exist. Never invent a folder.\n- `write_flow` mirrors flow mode's `set_flow_json`: pass `path`, optional `summary`, optional `description`, required `modules`, and optional `schema`, `preprocessor_module`, `failure_module`, `groups`, and `notes`. `summary` and `description` are top-level flow metadata (not part of the compact value `patch_flow_json` edits); the flow-structure arguments are JSON strings, matching the tool schema descriptions. When overwriting an existing flow, top-level flow settings (see below) are preserved from the current flow — use `patch_flow_json` to change them.\n- `read_workspace_item` returns a compact flow `value` object with `modules`, `schema`, `preprocessor_module`, `failure_module`, `groups`, `notes`, and any top-level flow settings that are set.\n- 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`: same_worker, preserve_step_tags, concurrent_limit, concurrency_key, concurrency_time_window_s, on_concurrency_limit, debounce_delay_s, debounce_key, debounce_args_to_accumulate, max_total_debouncing_time, max_total_debounces_amount, skip_expr, cache_ttl, cache_ignore_s3_path, delete_after_secs, timeout, flow_env, priority, early_return, chat_input_enabled. For example, `chat_input_enabled: true` marks a flow as chat-style (flow-as-chat); keep it intact when restructuring such a flow.\n- `modules` contains normal sequential modules. Use top-level `preprocessor_module` and `failure_module` for special modules; do not put `preprocessor` or `failure` in `modules`.\n- Every module needs a stable unique `id` and a useful `summary` when the schema supports it.\n- Prefer path/script/flow modules when composing existing workspace logic. Use rawscript modules only when new inline code is needed.\n- When writing rawscript module code, call `get_instructions` with `subject: \"script\"` and the rawscript language first.\n\n## Groups and notes\n\n- 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`.\n- 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.\n\n## Compact view: how rawscript bodies surface in tool I/O\n\n- `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.\"` so inline script bodies don't bloat tool I/O. Schema, groups, notes, preprocessor_module and failure_module are all shown in this view.\n- Inline rawscript content is **not** part of the JSON `patch_flow_json` sees. Edits to inline bodies happen via dedicated tools:\n - `read_flow_module_code(path, module_id)` — returns the raw inline script content for one module.\n - `set_flow_module_code(path, module_id, code)` — overwrites that module's inline script content; saves to the draft.\n- Use `patch_flow_json` for *structural* edits: module ids, paths, input_transforms, branch arrangement, summaries, preprocessor/failure swaps, schema/groups/notes. Use `set_flow_module_code` for changes inside a specific rawscript body.\n- When **adding a new rawscript module** with `patch_flow_json`, set its `content` to the placeholder `\"inline_script.\"` (matching the compact view) — never real code — then **immediately fill the body** with `set_flow_module_code(path, module_id, code)`. The module is saved with an empty body until you do; the tool result lists the module ids still awaiting code. A placeholder that names anything other than the module's own id or an existing rawscript module is rejected.\n- `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.\n - When overwriting an **existing** flow, set `\"content\": \"inline_script.\"` 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.\n\n\n# Windmill flow authoring reference\n\n# Windmill Flow Building Guide\n\n## OpenFlow Schema\n\nThe OpenFlow schema (openflow.openapi.yaml) is the source of truth for flow structure. Refer to OPENFLOW_SCHEMA for the complete type definitions.\n\n## Reserved Module IDs\n\n- `failure` - Reserved for failure handler module\n- `preprocessor` - Reserved for preprocessor module\n- `Input` - Reserved for flow input reference\n\n## Hard Structural Rules\n\nThese are strict Windmill schema rules. Follow them exactly.\n\n- `value.modules` is only for normal sequential steps\n- `value.preprocessor_module` and `value.failure_module` are special top-level fields inside `value`, not entries in `value.modules`\n- If a flow needs a preprocessor, create `value.preprocessor_module` with `id: preprocessor`\n- If a flow needs a failure handler, create `value.failure_module` with `id: failure`\n- Do NOT create regular modules inside `value.modules` named `preprocessor` or `failure`\n- `preprocessor_module` and `failure_module` only support `script` or `rawscript`\n- `preprocessor_module` runs before normal modules and cannot reference `results.*`\n- `failure_module` can use the `error` object with `error.message`, `error.step_id`, `error.name`, and `error.stack`\n- A flow whose `failure_module` runs still ends as failed, unless the handler returns an object with `recover: true`: the flow then ends as a success. This also holds when the failing step is inside a loop, a branch or a subflow. `recover` never changes which steps run; whether a loop or branch carries on past a failure is still decided by its own settings (`skip_failures`, `continue_on_error`)\n\nCorrect shape:\n\n```yaml\nvalue:\n preprocessor_module:\n id: preprocessor\n value:\n type: rawscript\n ...\n failure_module:\n id: failure\n value:\n type: rawscript\n ...\n modules:\n - id: process_event\n value:\n type: rawscript\n ...\n```\n\nIncorrect shape:\n\n```yaml\nvalue:\n modules:\n - id: preprocessor\n ...\n - id: process_event\n ...\n - id: failure\n ...\n```\n\n## Module ID Rules\n\n- Must be unique across the entire flow\n- Use underscores, not spaces (e.g., `fetch_data` not `fetch data`)\n- Use descriptive names that reflect the step's purpose\n\n## AI Agent Modules\n\nAn `aiagent` module runs an LLM that can call tools. Each entry of `value.tools` is a module-shaped\nobject with an extra `value.tool_type`: `flowmodule` for a script or inline script tool (or a nested\nagent or AI decision), `mcp` for an MCP server tool, `websearch` for web search, `question` for a\nbuilt-in `ask_question` tool (the agent stops, without holding a worker, until someone answers from\nthe run page or the chat; optional `value.timeout` in seconds, default 1800). Set\n`requires_approval: true` on a `flowmodule` or `mcp` tool to have a person approve or reject each of\nits calls before it runs. Set `background: true` on a `flowmodule` tool that runs long: the agent is\nanswered as soon as its job starts and keeps working, and gets the result in a later message,\nwaiting for it without holding a worker if it finishes its answer first. Prefer it to having the\nagent start jobs through a script or `runScriptByPath`, whose results it cannot wait on. For a tool\nthat is usually quick but sometimes long, set `background_after_secs: ` instead: the agent\nwaits that long for the result, then the call continues in the background.\n\n```json\n{\n \"id\": \"support_agent\",\n \"summary\": \"AI agent for customer support\",\n \"value\": {\n \"type\": \"aiagent\",\n \"input_transforms\": {\n \"provider\": {\n \"type\": \"static\",\n \"value\": { \"kind\": \"openai\", \"resource\": \"$res:f/ai_providers/openai\", \"model\": \"gpt-4o\" }\n },\n \"output_type\": { \"type\": \"static\", \"value\": \"text\" },\n \"user_message\": { \"type\": \"javascript\", \"expr\": \"flow_input.query\" },\n \"system_prompt\": { \"type\": \"static\", \"value\": \"You are a helpful assistant.\" }\n },\n \"tools\": [\n {\n \"id\": \"search_docs\",\n \"summary\": \"search_documentation\",\n \"description\": \"Search the product documentation. Use it whenever the user asks how a feature works.\",\n \"value\": {\n \"tool_type\": \"flowmodule\",\n \"type\": \"rawscript\",\n \"language\": \"bun\",\n \"content\": \"export async function main(query: string) { return ['doc1', 'doc2']; }\",\n \"input_transforms\": { \"query\": { \"type\": \"ai\" } }\n }\n }\n ]\n }\n}\n```\n\n- A flow cannot be a tool: a run offered one fails with `Unsupported tool`. Wrap it in a script\n that runs the flow\n- Each argument of a tool is either the model's or fixed. `{ \"type\": \"ai\" }` (or no value) lets the\n model fill it; a static value, an empty string included, fixes it and hides it from the model. Fix\n what the model must not choose, such as a resource, a table name or a limit\n- `provider` is an object, not a bare resource string: `{ \"kind\": ,\n \"resource\": \"$res:\", \"model\": }`. Required unless the module links to a saved\n agent through `value.agent`. Static is right for a flow run from a form; a chat flow wires its\n fields to flow inputs instead — see below\n\n### Chat-Mode Flows\n\nA flow with `value.chat_input_enabled: true` is run from a chat instead of a form: the composer\nsends one message per turn and renders the conversation. It needs a required `user_message` string\ninput, read by the agent. Any other flow input the composer does not edit itself is asked for\nunder Configure inputs.\n\n**A static `provider` gives a chat that cannot change its model.** Feed it from flow inputs\ninstead, either way round: one input carrying the whole object (`\"expr\": \"flow_input.model_config\"`)\nmakes every field editable, or wire it field by field to fix some and expose others. A field the\nchat can write becomes a control in the composer — a provider picker, a model list, a thinking\ncontrol — and a field left static is fixed, with no control drawn for it. `kind` is the one\nexception: the composer writes it only together with `resource`, since a provider is picked as a\npair, so a `kind` input wired on its own stays askable under Configure inputs and nothing the run\nneeds becomes unreachable.\n\n```json\n{\n \"id\": \"chat_agent\",\n \"value\": {\n \"type\": \"aiagent\",\n \"input_transforms\": {\n \"provider\": {\n \"type\": \"javascript\",\n \"expr\": \"({ kind: 'anthropic', resource: '$res:f/ai/claude', model: flow_input.model, reasoning_effort: flow_input.thinking })\"\n },\n \"user_message\": { \"type\": \"javascript\", \"expr\": \"flow_input.user_message\" },\n \"user_attachments\": { \"type\": \"javascript\", \"expr\": \"flow_input.files\" },\n \"memory\": { \"type\": \"static\", \"value\": { \"kind\": \"compaction\" } },\n \"streaming\": { \"type\": \"static\", \"value\": true },\n \"output_type\": { \"type\": \"static\", \"value\": \"text\" }\n },\n \"tools\": []\n }\n}\n```\n\n- Wiring field by field means one object literal whose values are literals or bare `flow_input.x`\n references. A spread, a call or a computed key leaves the composer unable to tell which input\n feeds which field, so it offers no control at all — a bare `flow_input.x` for the whole object\n is read instead as that one input carrying every field\n- A step linked to a saved agent (`agent` set) has no `provider` of its own. It exposes the same\n two controls through its `model` and `reasoning_effort` inputs, which replace what the agent\n saved: `\"model\": { \"type\": \"javascript\", \"expr\": \"flow_input.model\" }`. An empty model keeps the\n saved one, an empty effort sends none, and the provider resource always stays the agent's\n- `memory` is what lets the agent see earlier turns; without it every message starts from nothing\n- `streaming` on makes the answer and its thinking appear token by token instead of all at once\n- `user_attachments` points at a flow input typed as an array of s3 objects\n (`{ \"type\": \"array\", \"items\": { \"type\": \"object\", \"resourceType\": \"s3object\" } }`), so files\n sent with a message reach the agent\n- Running one needs a `memory_id` **query parameter** — not a flow argument — naming the\n conversation the turn belongs to: a fresh UUID starts one, reusing a UUID continues it. The chat\n supplies it itself; a run driven any other way has to pass it or the server refuses the job\n\n### Tool Naming Rules\n\nThese rules cover `flowmodule` tools, the ones the agent calls by name. A `websearch` or `question`\ntool's `summary` is a plain label (`Web Search`), and an `mcp` tool exposes the MCP\nserver's own tool names, so none is name-checked at all — leave those summaries as they are.\n\n- A flowmodule tool's `summary` is the **name the agent calls it by**, not a human label. Put the\n human-readable explanation in `description`\n- `summary` must match `^[a-zA-Z0-9_]+$`: letters, numbers and underscores only. No spaces, dashes,\n dots or accents — `search_documentation`, never `Search documentation`\n- Always set `summary`. It must be unique among that agent's tools, and must not be one of the\n reserved ids (`do`, `bg`, `ctx`, `state`, `if`, `else`, `for`, `delete`, `while`, `new`, `in`,\n `failure`, `preprocessor`, `as`, `Input`, `Result`, `Trigger`)\n- A tool name outside that character set fails any run that offers the tool to the agent, with `Invalid tool name`.\n The flow write tools refuse such a name.\n- Tool `id` follows the same rules as any module ID — unique across the flow, underscores not spaces\n- `description` is optional free text telling the agent when and how to call the tool. Set it\n whenever the name alone does not make that obvious; it overrides the description derived from the\n underlying script\n\n## AI Decision Modules\n\nAn `aidecision` module asks a decision model (TypeSafe's Jev, Cloudflare's Clef, or OpenAI's or Gemini's Decisions API) typed questions about a `state` and\nanswers each with calibrated probabilities instead of text. Prefer it over an `aiagent` when the step\nis a judgment (classify, route, score or a yes/no check) that needs no tools and no free text: it\nis faster, cheaper, and its answers have a fixed shape.\n\n```json\n{\n \"id\": \"triage\",\n \"summary\": \"Classify the ticket\",\n \"value\": {\n \"type\": \"aidecision\",\n \"input_transforms\": {\n \"provider\": {\n \"type\": \"static\",\n \"value\": { \"kind\": \"typesafe\", \"resource\": \"$res:f/ai/typesafe\", \"model\": \"jev-latest\" }\n },\n \"state\": { \"type\": \"javascript\", \"expr\": \"flow_input.message\" },\n \"questions\": {\n \"type\": \"static\",\n \"value\": {\n \"intent\": {\n \"type\": \"choice\",\n \"instructions\": \"What does the customer want?\",\n \"criteria\": { \"refund\": \"Money back\", \"bug\": \"Something is broken\", \"other\": \"Anything else\" }\n },\n \"urgency\": {\n \"type\": \"score\",\n \"instructions\": \"How urgent is the ticket?\",\n \"criteria\": [\"Can wait\", \"This week\", \"Today\", \"Right now\"]\n },\n \"angry\": { \"type\": \"noul\", \"instructions\": \"Is the customer angry?\" }\n }\n }\n }\n }\n}\n```\n\n- `provider.kind` is `typesafe` (`model` `jev-latest` unless a version is pinned), `cloudflare`\n (`model` `clef`, or `clef-flash` for faster answers), `openai` (`model` `gpt-6-luna`, never a\n chat model) or `googleai` (`model` `gemini-decision-1`, never a chat model); the resource is of\n that same type\n- `state` is the content to evaluate: usually a text, such as the message to classify. To combine\n several values, pass an object with descriptive keys holding only what the questions need\n (`({ message: flow_input.message, plan: results.get_account.plan })`); an array of strings also works\n- `questions` maps each question name to `{ type, instructions, criteria }`:\n - `choice`: `criteria` maps each option to its description (up to 255 options). The answer has\n `choice`, `probabilities` and `confidence`\n - `score`: `criteria` is an ordered array of 2 to 10 level descriptions. The answer has `score`,\n `legend`, `probabilities` and `confidence`\n - `noul`: yes/no, `criteria` optionally `{ \"true\": ..., \"false\": ... }` descriptions. The answer has\n `noul`, the probability of yes from 0 to 1\n- The result is `{ output, model, usage }` with `output` keyed by question name, so a later step\n reads `results.triage.output.intent.choice`, `results.triage.output.urgency.score` or\n `results.triage.output.angry.noul > 0.7`\n- On `openai` the same `questions` are translated for its Decisions API and the answers read the\n same way (`choice`, `score`, `noul`), except that `probabilities` is a list of\n `{ value, probability }` (plus `label` on a score) and a score has no `legend`. A question OpenAI\n refuses to answer fails the step. A `state` that is\n an array of user messages (`[{ role: \"user\", content: [{ type: \"input_text\", text }, { type: \"input_image\", image_url: \"data:image/png;base64,...\" }] }]`)\n is sent as is, which is how an image is evaluated; any other object or array is sent as JSON text\n- On `googleai` the `questions` and answers are the same as on `typesafe`. If Gemini blocks the\n input, the step fails. A `state` that is a Gemini content block or an array of them (`[{ type: \"text\", text }, { type: \"image\", mime_type: \"image/png\", data: \"\" }]`,\n where `image`, `audio`, `video` and `document` blocks take `data` or `uri`) is sent as is, which\n is how an image or a document is evaluated; any other object or array is sent as JSON text\n\n### Branching on the Answers\n\nTo route on the answers, put a `branchone` right after the decision, one branch per option, with\neach `expr` reading the decision by id:\n\n```json\n{\n \"id\": \"route\",\n \"value\": {\n \"type\": \"branchone\",\n \"branches\": [\n { \"summary\": \"refund\", \"expr\": \"results.triage.output.intent.choice === 'refund'\", \"modules\": [...] },\n { \"summary\": \"bug\", \"expr\": \"results.triage.output.intent.choice === 'bug'\", \"modules\": [...] }\n ],\n \"default\": [...]\n }\n}\n```\n\nFor a yes/no question, one branch with `\"expr\": \"results.triage.output.angry.noul >= 0.5\"` (tune the\nthreshold as needed) and the `default` as the \"no\" path.\n\n### As an Agent Tool\n\nAn `aidecision` can be a `flowmodule` tool of an `aiagent` (`\"tool_type\": \"flowmodule\", \"type\":\n\"aidecision\"`): set `state` to `{ \"type\": \"ai\" }` so the calling model supplies it, and only `output`\ngoes back to the model. The Tool Naming Rules apply to its `summary`. Only a flow's own agent step\ncan call one, not an agent used as a tool.\n\n## Common Mistakes to Avoid\n\n- Missing `input_transforms` - Rawscript parameters won't receive values without them\n- Referencing future steps - `results.step_id` only works for steps that execute before the current one\n- Duplicate module IDs - Each module ID must be unique in the flow\n- AI agent flowmodule tool names with spaces - `summary` is the tool name and only accepts letters, numbers and underscores\n\n## Data Flow Between Steps\n\n- `flow_input.property` - Access flow input parameters\n- `results.step_id` - Access output from a previous step only when that step result is in scope\n- `results.step_id.property` - Access specific property from a previous step output only when that step result is in scope\n- `flow_input.iter.value` - Current iteration value inside a `forloopflow`; in a `whileloopflow` it is just the iteration index (a plain number, same as `flow_input.iter.index`)\n- `flow_input.iter.index` - Current loop index when inside a loop (`forloopflow` or `whileloopflow`)\n- After a suspend step (approval), the next step's javascript expressions also get:\n - `resume` - the last resume payload (the resume form values); with `continue_on_disapprove_timeout`, a disapproval or timeout yields `{ error: { name: \"SuspendedDisapproved\" | \"SuspendedTimedOut\", message } }` instead, plus `reason` on a disapproval whose approver gave one\n - `resumes` - every resume payload, in arrival order\n - `approvers` - a plain array of strings, one per resume: for a resume through the `resume`/`cancel` URL from `getResumeUrls(approver)`, the `approver` passed there if any; otherwise (including the `approvalPage` link) the resuming user's username, else `\"anonymous\"`, e.g. `approvers[0]`. It is NOT the `{ resume_id, approver }` objects stored in the flow status, so `approvers[0].approver` is always undefined\n\n## Loop Structure Rules\n\n- A `forloopflow` runs its `modules` once per element of `iterator`, a javascript expression returning an array (e.g. `results.get_items`); `parallel: true` runs the iterations concurrently, and `skip_failures: true` carries on past a failed iteration\n- When iterations are items a user will look for in a run (customers, files, ids), set `iteration_label` on the `forloopflow` value to a javascript expression naming each one, e.g. `flow_input.iter.value.name`; it only labels iterations in the run viewer and never changes what runs\n- For `whileloopflow`, break the loop with a module-level `stop_after_if`: on the loop module itself, or on an inner step (required when that step carries state via its own `results` — see below)\n- `stop_after_if` is always a sibling of `id` and `value` on a flow module — never a direct key of the loop's `value` object\n- `stop_after_all_iters_if` is for checks after the whole loop finishes, not the normal per-iteration break condition\n- `stop_after_if` is evaluated after each iteration: on the loop module, `result` is that iteration's result (what its last step returned); on an inner step, it is that step's result\n- `flow_input.iter.value` in a `whileloopflow` is just the iteration index (same number as `flow_input.iter.index`) — it never carries state, so `flow_input.iter.value.` is always undefined and a loop whose stop condition depends on it never terminates\n- To carry state across iterations, a step reads its own previous-iteration result via `results.` with a first-iteration fallback (e.g. `results.b ?? flow_input.start`) — but then the loop's `stop_after_if` MUST sit on that inner step, not on the loop module: a body that is exactly one plain step with the stop condition on the loop module runs on a fast path where `results.` is null on every iteration and the loop never terminates (bodies with 2+ steps, or whose single step has its own `stop_after_if`, retry or similar, resolve `results` across iterations regardless of stop placement)\n- To cap a `whileloopflow`, set `max_iterations` and/or `max_duration_secs` (seconds since the first iteration started) on the loop's `value`, rather than encoding the bound into `stop_after_if`. Both are checked after each iteration, so a running iteration is never interrupted and the loop can exceed `max_duration_secs` by at most one iteration (bound an iteration with its steps' `timeout`); whichever is reached first, unless `stop_after_if` stopped the loop at that iteration, fails the loop with `{ error: { name: \"LoopExhausted\", message } }`. To handle it, set `continue_on_error: true` on the loop and branch in the next step on `results..error?.name === \"LoopExhausted\"` (only the step right after the loop sees the error there; later steps see the iterations' results); retries and the failure module apply as for any step failure. For a pause between iterations, set `sleep` on the body's step\n- For state that is just a counter, derive it from the index instead (e.g. `flow_input.iter.index + 1`) — that works in every configuration, including with `stop_after_if` on the loop module\n- If the user asks for a final scalar/object after a loop, add a normal step after the loop that extracts the final value from the loop result instead of returning the whole loop result array\n\nCorrect `whileloopflow` shape:\n\n```yaml\n- id: loop_until_done\n stop_after_if:\n expr: result.done === true\n skip_if_stopped: false\n value:\n type: whileloopflow\n skip_failures: false\n modules:\n - id: advance_state\n value:\n type: rawscript\n input_transforms:\n count:\n type: javascript\n expr: flow_input.iter.index + 1\n- id: return_final_state\n value:\n type: rawscript\n input_transforms:\n final_state:\n type: javascript\n expr: results.loop_until_done[results.loop_until_done.length - 1]\n```\n\nCorrect `whileloopflow` shape carrying state via `results` (stop condition on the inner step):\n\n```yaml\n- id: loop_until_done\n value:\n type: whileloopflow\n skip_failures: false\n modules:\n - id: advance_state\n stop_after_if:\n expr: result.done === true\n skip_if_stopped: false\n value:\n type: rawscript\n input_transforms:\n state:\n type: javascript\n expr: results.advance_state ?? flow_input.initial_state\n```\n\nIncorrect `whileloopflow` patterns:\n\n```yaml\n- id: loop_until_done\n value:\n type: whileloopflow\n stop_after_if:\n expr: result.done === true\n```\n\n```yaml\ninput_transforms:\n state:\n type: javascript\n # iter.value is a number (the iteration index); there is no previous-iteration state\n expr: flow_input.iter.value.count\n```\n\n```yaml\ninput_transforms:\n final_state:\n type: javascript\n expr: results.loop_until_done\n```\n\n## Approval / Suspend Structure\n\nAn approval step is a normal **script** step (`type: rawscript` or `type: script`) that is turned into an approval by adding a module-level `suspend`. Its script calls `wmill.getResumeUrls(approver)` to generate the secret resume/cancel URLs and returns them so they can be sent to the approver(s) (Slack, email, etc.) or approved from the run page.\n\n- `suspend` belongs on the flow module object itself, as a sibling of `id` and `value`\n- Never put `suspend` inside `value`\n- Do NOT use `type: identity` for an approval step. An identity step suspends but never produces the resume URLs, so approvers have no link to act on — it is not a functional approval.\n\nCorrect shape:\n\n```yaml\n- id: request_approval\n suspend:\n required_events: 1\n resume_form:\n schema:\n type: object\n properties:\n comment:\n type: string\n required: [comment]\n value:\n type: rawscript\n language: bun\n input_transforms:\n approver:\n type: static\n value: ''\n content: |\n import * as wmill from \"windmill-client\"\n\n export async function main(approver?: string) {\n const urls = await wmill.getResumeUrls(approver)\n // send urls.resume / urls.cancel to the approver(s), e.g. via Slack or email\n return urls\n }\n```\n\nIncorrect shape (suspend misplaced inside `value`):\n\n```yaml\n- id: request_approval\n value:\n type: rawscript\n suspend:\n required_events: 1\n```\n\nIncorrect shape (identity has no resume URLs — not a real approval):\n\n```yaml\n- id: request_approval\n suspend:\n required_events: 1\n value:\n type: identity\n```\n\n## Branch Result Scope Rules\n\n- A `branchone` runs the first of its `branches` whose `expr` is true, in order, and its `default` modules when none is; a `branchall` runs every branch (concurrently with `parallel: true`)\n- Inside a branch, you may reference earlier outer steps and earlier steps in the same branch\n- Outside a `branchone`, do NOT reference ids of steps that only exist inside its branches or default branch. Use `results.` instead\n- Outside a `branchall`, do NOT reference ids of steps inside its branches. Use `results.` instead\n- If downstream steps need a stable shape after a branch, make each branch return the same fields\n- When needed, add a normalization step immediately after the branch and consume `results.` there\n\nCorrect after `branchone`:\n\n```yaml\n- id: route_order\n value:\n type: branchone\n ...\n- id: send_confirmation\n value:\n input_transforms:\n routed:\n type: javascript\n expr: results.route_order\n```\n\nIncorrect after `branchone`:\n\n```yaml\nexpr: results.create_shipment\nexpr: results.create_backorder\n```\n\nCorrect after `branchall`:\n\n```yaml\n- id: enrich_parallel\n value:\n type: branchall\n parallel: true\n ...\n- id: combine_data\n value:\n input_transforms:\n enrichments:\n type: javascript\n expr: results.enrich_parallel\n```\n\n## Input Transforms\n\nEvery rawscript module needs `input_transforms` to map function parameters to values:\n\nStatic transform (fixed value):\n{\"param_name\": {\"type\": \"static\", \"value\": \"fixed_string\"}}\n\nJavaScript transform (dynamic expression):\n{\"param_name\": {\"type\": \"javascript\", \"expr\": \"results.previous_step.data\"}}\n\n## Resource References\n\n- For flow inputs: Use type `\"object\"` with format `\"resource-{type}\"` (e.g., `\"resource-postgresql\"`)\n- For step inputs: Use static value `\"$res:path/to/resource\"`\n\n## Reusing Existing Scripts and Flows\n\nUnless the user asked for new code, look for a workspace script or flow that already does a step's job before writing it, and reuse it by path instead of copying its logic into a rawscript:\n\n- a workspace script: `type: script` with `path` (e.g. `f/folder/send_email`)\n- a workspace flow, run as a subflow: `type: flow` with `path`\n- a Hub script: `type: script` with a `hub///` path\n\nThe step's `input_transforms` must cover the reused item's inputs, so read its input schema first.\n\n## Additional Prompt for AI\n\nA flow's input schema may carry a top-level `prompt_for_ai` string, as a script's can: its author's instructions to an AI choosing the inputs. Follow it when you pick arguments to run that flow, and keep it when you rewrite the schema.\n\n## Organizing Flows: Groups and Notes\n\nGroups and notes shape how a flow reads in the editor; neither changes what it does.\n\n**Segment every non-trivial flow into groups without waiting to be asked.** Whenever a flow has more than a couple of steps, or consecutive steps form a stage (\"fetch\", \"transform\", \"notify\"), put them in a group, and aim for every meaningful step to belong to one. Use notes sparingly, for flow-wide information that belongs to no span of steps: the flow's purpose, key assumptions, warnings, TODOs. One note is usually enough; never label a run of steps with a note, which is what a group is for.\n\n`value.groups` lists the groups, each spanning the steps from `start_id` to `end_id`:\n\n- `start_id`, `end_id` (required): ids of the group's first and last step; the same id for both makes a one-step group\n- `summary`: the group's title\n- `note`: markdown shown under the title\n- `color`: one of `yellow`, `blue`, `green`, `purple`, `pink`, `orange`, `red`, `cyan`, `lime`, `gray`, never a hex code or CSS color; leave it out and the editor picks one\n- `autocollapse`: `true` shows the group collapsed by default\n\nThe editor refuses to draw a flow whose groups break any of these rules:\n\n- `start_id` and `end_id` are steps of the same list: both top-level, or both in the same loop body or branch. A group can hold a loop or branch step whole, but cannot start outside one and end inside it\n- `start_id` does not come after `end_id` in that list\n- groups nest (one entirely inside another) but never partly overlap, and no two groups share both `start_id` and `end_id`\n- groups hold ordinary steps only: never `preprocessor`, `failure`, `Input`, `Result`, `Trigger`, or an AI agent's tools\n\n`value.notes` lists sticky notes, each with a unique `id`, markdown `text`, a `color` from the same list, and `type: free`. The `group` note type is deprecated; use `value.groups` instead.\nLeave a note's `position` and `size` out and they are filled in for you.\n\n## Final Structural Self-Check\n\nBefore finalizing a flow, verify:\n\n- any preprocessor is in `value.preprocessor_module`\n- any failure handler is in `value.failure_module`\n- any approval step has module-level `suspend`\n- no downstream step references inner branch step ids from outside the branch\n- every AI agent flowmodule tool has a unique `summary` made only of letters, numbers and underscores\n- every group starts and ends on steps of the same list, start before end, nesting without partial overlap\n\n## S3 Object Operations\n\nWindmill provides built-in support for S3-compatible storage operations.\n\nTo accept an S3 object as flow input:\n\n```json\n{\n \"type\": \"object\",\n \"properties\": {\n \"file\": {\n \"type\": \"object\",\n \"format\": \"resource-s3_object\",\n \"description\": \"File to process\"\n }\n }\n}\n```\n\n## Using Resources in Flows\n\nOn Windmill, credentials and configuration are stored in resources. Resource types define the format of the resource.\n\n### As Flow Input\n\nIn the flow schema, set the property type to `\"object\"` with format `\"resource-{type}\"`:\n\n```json\n{\n \"type\": \"object\",\n \"properties\": {\n \"database\": {\n \"type\": \"object\",\n \"format\": \"resource-postgresql\",\n \"description\": \"Database connection\"\n }\n }\n}\n```\n\n### When No Resource Type Fits\n\nA 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.\n\n- 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.\n- Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it.\n- A plain variable is fine when the user asks for it.\n\n### As Step Input (Static Reference)\n\nReference a specific resource using `$res:` prefix:\n\n```json\n{\n \"database\": {\n \"type\": \"static\",\n \"value\": \"$res:f/folder/my_database\"\n }\n}\n```\n\n\n## OpenFlow Schema\n\n{\"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\"},\"on_concurrency_limit\":{\"type\":\"string\",\"enum\":[\"queue\",\"fail\"],\"description\":\"What a run of this flow does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed, like any failed step.\"},\"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\"},\"timeout\":{\"type\":\"integer\",\"description\":\"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error.\"},\"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 after this step completes, before the next step starts (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\"},\"preview_only\":{\"type\":\"boolean\",\"description\":\"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run.\"}}},\"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\"},\"on_concurrency_limit\":{\"type\":\"string\",\"enum\":[\"queue\",\"fail\"],\"description\":\"What a run of this step does when its concurrency limit is reached. `queue` (default) re-queues it to a later slot, `fail` ends it immediately as failed.\"},\"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\"},\"iteration_label\":{\"description\":\"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters\",\"$ref\":\"#/components/schemas/InputTransform\"}},\"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\"},\"max_iterations\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'\"},\"max_duration_secs\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'\"}},\"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\"},\"parallelism\":{\"description\":\"Maximum number of branches running at once when parallel=true. Can be static number or expression\",\"$ref\":\"#/components/schemas/InputTransform\"}},\"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, websearch or question 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.\"},\"requires_approval\":{\"type\":\"boolean\",\"description\":\"Flowmodule and mcp tools only. Each call waits for a person to approve or reject it from the flow's run page or chat, without the agent holding a worker. Calls in the same turn that do not require approval run right away. A rejected call, or one nobody answers within 30 minutes, is reported to the AI as not run.\"},\"background\":{\"type\":\"boolean\",\"description\":\"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result.\"},\"background_after_secs\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message.\"},\"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\"},{\"$ref\":\"#/components/schemas/QuestionToolValue\"}],\"discriminator\":{\"propertyName\":\"tool_type\",\"mapping\":{\"flowmodule\":\"#/components/schemas/FlowModuleTool\",\"mcp\":\"#/components/schemas/McpToolValue\",\"websearch\":\"#/components/schemas/WebsearchToolValue\",\"question\":\"#/components/schemas/QuestionToolValue\"}}},\"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\"]},\"QuestionToolValue\":{\"type\":\"object\",\"description\":\"Built-in tool the AI calls as ask_question: the agent stops, releasing its worker, until someone answers from the flow's run page or chat or the question times out, then resumes with the answer as the tool result.\",\"properties\":{\"tool_type\":{\"type\":\"string\",\"enum\":[\"question\"]},\"timeout\":{\"type\":\"integer\",\"description\":\"Seconds to wait for an answer before the question is reported to the AI as timed out. Defaults to 1800.\"}},\"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 or Gemini'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_labels\":{\"type\":\"array\",\"description\":\"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing\",\"items\":{\"type\":\"string\",\"nullable\":true}},\"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\":[\"approval\"]},\"call_id\":{\"type\":\"string\"},\"calls\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"function_name\":{\"type\":\"string\"},\"arguments\":{}},\"required\":[\"function_name\",\"arguments\"]}},\"expires_at\":{\"type\":\"string\",\"format\":\"date-time\"}},\"required\":[\"type\",\"call_id\",\"calls\",\"expires_at\"]},{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"question\"]},\"call_id\":{\"type\":\"string\"},\"question\":{\"type\":\"string\"},\"choices\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"answers the model proposes; a free-text answer is always possible\"},\"multi_select\":{\"type\":\"boolean\",\"description\":\"whether several choices can be picked together\"},\"expires_at\":{\"type\":\"string\",\"format\":\"date-time\"}},\"required\":[\"type\",\"call_id\",\"question\",\"expires_at\"]},{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"message\"]}},\"required\":[\"content\",\"type\"]}]}},\"agent_actions_success\":{\"type\":\"array\",\"description\":\"The outcome of each agent action, by position. null while a background tool call is still running.\",\"items\":{\"type\":\"boolean\",\"nullable\":true}}},\"required\":[\"type\"]}}", "resource": "# Global draft resource & variable instructions\n\n- Global mode writes complete draft payloads only; it does not save, deploy, run, scaffold local files, or generate metadata.\n- A resource draft is a workspace item: `{ type: 'resource', path, summary?, value, isDraft }`. `value` is a CreateResource body: `{ path, value, description?, resource_type, labels? }` where the inner `value` is the resource type's data shape.\n- Reading a variable returns `{ type: 'variable', path, summary?, isSecret, isDraft }` — never its value, secret or not. `isSecret` tells you whether the value is encrypted.\n- `write_variable` takes `{ path, value?, is_secret?, description?, is_oauth?, expires_at?, value_valid_until?, labels? }`. Creating a variable needs `value` and `is_secret`; editing one needs only the fields you are changing. Omitting `value` keeps the stored value, which is the only way to edit a secret variable — you cannot read its value, so passing any `value` you did not get from the user destroys it.\n- For secret fields in a resource value, create the variable with `write_variable` and `is_secret: true`, and deploy it before the resource (see \"Secrets\" in the reference below).\n- Reference formats inside resource values: `$var:g/all/name` (global), `$var:u/user/name` (user), `$var:f/folder/name` (folder). Reference another resource with `$res:path/to/resource`. The same strings are also how a resource or variable is passed as a run argument (see the run-argument rule in the resource reference below); what they are never valid as is a variable's own value.\n- Use `search_resource_types` to discover valid `resource_type` names and their JSON Schemas. Match the resource value to that schema.\n- For an agent (an `ai_agent` resource), call `get_instructions` with `subject: \"agent\"` instead.\n- For OAuth resources, the `is_oauth: true` flag is managed by Windmill's OAuth flow; global mode generally creates manual resources, not OAuth ones.\n\n# Windmill resource & variable reference\n\n# Windmill Resources\n\nResources store credentials and configuration for external services.\n\n## Resource Structure\n\n```json\n{\n \"value\": {\n \"host\": \"db.example.com\",\n \"port\": 5432,\n \"user\": \"admin\",\n \"password\": \"$var:g/all/db_password\",\n \"dbname\": \"production\"\n },\n \"description\": \"Production PostgreSQL database\",\n \"resource_type\": \"postgresql\"\n}\n```\n\n## Required Fields\n\n- `value` - Object containing the resource configuration\n- `resource_type` - Name of the resource type (e.g., \"postgresql\", \"slack\")\n\n## Agents\n\nAn agent, as the Agents page lists it, is a resource of type `ai_agent`. Its value holds the\nagent's provider, system prompt, tools and memory settings, and a flow step uses a saved agent by\nlinking its path.\n\n## Variable References\n\nReference variables in resource values:\n\n```json\n{\n \"value\": {\n \"api_key\": \"$var:g/all/api_key\",\n \"secret\": \"$var:u/admin/secret\"\n }\n}\n```\n\n**Reference formats:**\n- `$var:g/all/name` - Global variable\n- `$var:u/username/name` - User variable\n- `$var:f/folder/name` - Folder variable\n\n## Secrets\n\nNever put a secret (password, API key, token) inline in a resource value. Store it in a secret variable and reference that variable as `$var:`.\n\n- `$var:` is a reference, not a value: it resolves to the variable's value at run time. Never invent a value for a variable.\n- A resource that references a variable needs the variable to exist first, so create or deploy the variable before the resource.\n\n## Resource References\n\nReference other resources:\n\n```json\n{\n \"value\": {\n \"database\": \"$res:f/databases/postgres\"\n }\n}\n```\n\n## Passing a Resource or Variable as a Run Argument\n\nA script or flow argument typed as a resource (schema `format: resource-`) is passed as\nthe **bare string** `$res:` — the whole argument value. Same for a variable, with\n`$var:`. This applies everywhere job arguments are supplied: `wmill script run/preview`,\n`wmill flow run/preview`, the `runScriptByPath` / `runFlowByPath` API, a schedule's `args`, a\ntrigger's configured static args.\n\n```json\n{\n \"db\": \"$res:f/databases/postgres_prod\",\n \"api_token\": \"$var:g/all/api_token\"\n}\n```\n\nThe reference is resolved when the job runs, under the job's run-as identity — the caller for an\nordinary run, but the configured principal for a schedule, a trigger, or a runnable set to run on\nbehalf of someone else. The run fails if that identity cannot read the referenced resource or\nvariable.\n\n**Never wrap it in an object.** The resolver only rewrites a JSON value that *is* a string\nstarting with `$res:` / `$var:`; keys are never inspected. These are all wrong and are passed\nthrough to the script unchanged:\n\n```json\n{ \"db\": { \"$res\": \"f/databases/postgres_prod\" } }\n{ \"db\": { \"resource\": \"f/databases/postgres_prod\" } }\n{ \"db\": \"f/databases/postgres_prod\" }\n```\n\nThe string may sit anywhere a string can — a top-level argument, a nested object field\n(`{ \"gh_auth\": { \"token\": \"$var:g/all/gh_token\" } }`), or an array element (array elements are\nwalked only while nested at most two levels deep, and only for arrays of at most 1000 items).\nThe prefix must be on the string itself.\n\n## Common Resource Types\n\n### PostgreSQL\n```json\n{\n \"resource_type\": \"postgresql\",\n \"value\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"user\": \"postgres\",\n \"password\": \"$var:g/all/pg_password\",\n \"dbname\": \"windmill\",\n \"sslmode\": \"prefer\"\n }\n}\n```\n\n### MySQL\n```json\n{\n \"resource_type\": \"mysql\",\n \"value\": {\n \"host\": \"localhost\",\n \"port\": 3306,\n \"user\": \"root\",\n \"password\": \"$var:g/all/mysql_password\",\n \"database\": \"myapp\"\n }\n}\n```\n\n### Slack\n```json\n{\n \"resource_type\": \"slack\",\n \"value\": {\n \"token\": \"$var:g/all/slack_token\"\n }\n}\n```\n\n### AWS S3\n```json\n{\n \"resource_type\": \"s3\",\n \"value\": {\n \"bucket\": \"my-bucket\",\n \"region\": \"us-east-1\",\n \"accessKeyId\": \"$var:g/all/aws_access_key\",\n \"secretAccessKey\": \"$var:g/all/aws_secret_key\"\n }\n}\n```\n\n### HTTP/API\n```json\n{\n \"resource_type\": \"http\",\n \"value\": {\n \"baseUrl\": \"https://api.example.com\",\n \"headers\": {\n \"Authorization\": \"Bearer $var:g/all/api_token\"\n }\n }\n}\n```\n\n### Kafka\n```json\n{\n \"resource_type\": \"kafka\",\n \"value\": {\n \"brokers\": \"broker1:9092,broker2:9092\",\n \"sasl_mechanism\": \"PLAIN\",\n \"security_protocol\": \"SASL_SSL\",\n \"username\": \"$var:g/all/kafka_user\",\n \"password\": \"$var:g/all/kafka_password\"\n }\n}\n```\n\n### NATS\n```json\n{\n \"resource_type\": \"nats\",\n \"value\": {\n \"servers\": [\"nats://localhost:4222\"],\n \"user\": \"$var:g/all/nats_user\",\n \"password\": \"$var:g/all/nats_password\"\n }\n}\n```\n\n### MQTT\n```json\n{\n \"resource_type\": \"mqtt\",\n \"value\": {\n \"host\": \"mqtt.example.com\",\n \"port\": 8883,\n \"username\": \"$var:g/all/mqtt_user\",\n \"password\": \"$var:g/all/mqtt_password\",\n \"tls\": true\n }\n}\n```\n\n## When No Resource Type Fits\n\nThe Windmill Hub publishes resource types for most services, and an instance gets them by syncing with the hub. When none fits the service:\n\n- 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.\n- 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.\n- 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.\n\n## Custom Resource Types\n\nA 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.\n\nCreate custom resource types with JSON Schema:\n\n```json\n{\n \"name\": \"c_custom_api\",\n \"schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"base_url\": {\"type\": \"string\", \"format\": \"uri\"},\n \"api_key\": {\"type\": \"string\"},\n \"timeout\": {\"type\": \"integer\", \"default\": 30}\n },\n \"required\": [\"base_url\", \"api_key\"]\n },\n \"description\": \"Custom API connection\"\n}\n```\n\nSave as: `c_custom_api.resource-type.json`\n\n## OAuth Resources\n\nOAuth resources are managed through the Windmill UI and marked:\n\n```json\n{\n \"is_oauth\": true,\n \"account\": 123\n}\n```\n\nOAuth tokens are automatically refreshed by Windmill.\n\n## Using Resources in Scripts\n\n### TypeScript (Bun/Deno)\n```typescript\nexport async function main(db: RT.Postgresql) {\n // db contains the resource values\n const { host, port, user, password, dbname } = db;\n}\n```\n\n### Python\n```python\nclass postgresql(TypedDict):\n host: str\n port: int\n user: str\n password: str\n dbname: str\n\ndef main(db: postgresql):\n # db contains the resource values\n pass\n```\n\n", - "app": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- App drafts are addressed by workspace path. Follow the path conventions in the system prompt: default to `u//` for bare names; only use `f//` when the folder is known to exist. The first write tool snapshots the workspace app onto the draft, and subsequent writes accumulate.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) 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 the user each of its questions, 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.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- Backend inline runnables are addressed as `backend//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? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- 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.\n- The authoring reference below carries the TypeScript SDK. For a `python3` runnable, call `get_instructions` again with `subject: \"app\"` and `language: \"python3\"`.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- 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.\n- 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`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse 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.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe 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.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render()\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**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`.\n\n**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.\n\n**Read the page's context from `window.ctx`**: `ctx` is the viewer (absent for anonymous visitors), `workspace` and `path` the app's (`path` is not set under `wmill app dev`), and `query` the page URL's query parameters as strings (`…/apps/get/u/me/app?customer=42` gives `window.ctx.query.customer === '42'`, and no query gives `{}`). Read it there, not from `window.location`, which in a sandboxed app is not the page's address. It is read once when the app loads.\n\n**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.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode or a saved agent\n\nA 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.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@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.\n\n#### A saved agent: an `agent` runnable\n\nChat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not:\n\n```json\n{ \"chat\": { \"type\": \"agent\", \"path\": \"f/support/agent\" } }\n```\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\nimport * as wmill from './wmill'\n\nconst chat = useWindmillChat({ wmill, runnable: 'chat' })\n```\n\n`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message`; the chat passes the conversation id as `backendAsync.<key>(args, { memoryId })`: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.<key>({ user_message })`, it is a single run with no conversation, for a one-off question; `backend.<key>(args, { memoryId })` waits for the reply of a conversation turn. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of five types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn 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.\n\n#### The `wmill` client is already authenticated\n\nAn 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.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript / agent)\n\nWhen `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `previous_messages` when its memory is off.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew 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.\n\nInside 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.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA 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.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData 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.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **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.\n4. **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.\n5. **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`.\n6. **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.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`.\n\n\n# TypeScript SDK (windmill-client)\n\nImport: import * as wmill from 'windmill-client'\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe helpers below are the surface to prefer. For an endpoint none of them covers, import the\ngenerated service classes (JobService, ScriptService, ...) from 'windmill-client' — they are not\nlisted here but they do exist. What does not exist is a helper name you guessed at: if it is\nneither listed below nor a service method, do not call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`process.env.WM_END_USER_EMAIL || process.env.WM_EMAIL`. WM_END_USER_EMAIL is the app viewer when\nthe run was triggered from an app and empty otherwise (both variables are always defined), WM_EMAIL\nis the user the job is permissioned as. WM_USERNAME is the matching username.\n\nworkerHasInternalServer(): boolean\n\n/**\n * Initialize the Windmill client with authentication token and base URL\n * @param token - Authentication token (defaults to WM_TOKEN env variable)\n * @param baseUrl - API base URL (defaults to BASE_INTERNAL_URL or BASE_URL env variable)\n */\nsetClient(token?: string, baseUrl?: string): void\n\n/**\n * Create a client configuration from env variables\n * @returns client configuration\n */\ngetWorkspace(): string\n\n/**\n * Get a resource value by path\n * @param path path of the resource, default to internal state path\n * @param undefinedIfEmpty if the resource does not exist, return undefined instead of throwing an error\n * @returns resource value\n */\nasync getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>\n\n/**\n * Get the true root job id\n * @param jobId job id to get the root job id from (default to current job)\n * @returns root job id\n */\nasync getRootJobId(jobId?: string): Promise<string>\n\n/**\n * Run a script synchronously by its path and wait for the result\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByPath(path: string, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Run a script synchronously by its hash and wait for the result\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByHash(hash_: string, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Append a text to the result stream\n * @param text text to append to the result stream\n */\nappendToResultStream(text: string): void\n\n/**\n * Stream to the result stream\n * @param stream stream to stream to the result stream\n */\nasync streamResult(stream: AsyncIterable<string>): Promise<void>\n\n/**\n * Run a flow synchronously by its path and wait for the result\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Flow execution result\n */\nasync runFlow(path: string | null = null, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Wait for a job to complete and return its result\n * @param jobId - ID of the job to wait for\n * @param verbose - Enable verbose logging\n * @returns Job result when completed\n */\nasync waitJob(jobId: string, verbose: boolean = false): Promise<any>\n\n/**\n * Get the result of a completed job\n * @param jobId - ID of the completed job\n * @returns Job result\n */\nasync getResult(jobId: string): Promise<any>\n\n/**\n * Get the result of a job if completed, or its current status\n * @param jobId - ID of the job\n * @returns Object with started, completed, success, and result properties\n */\nasync getResultMaybe(jobId: string): Promise<any>\n\n/**\n * Cancel a queued or running job by ID.\n * @param jobId - UUID of the job to cancel\n * @param reason - Optional reason for cancellation\n * @returns Response message from the cancel endpoint\n */\nasync cancelJob(jobId: string, reason: string | undefined = undefined): Promise<string>\n\n/**\n * Run a script asynchronously by its path\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByPathAsync(path: string, args: Record<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\n\n/**\n * Run a script asynchronously by its hash\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByHashAsync(hash_: string, args: Record<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\n\n/**\n * Run a flow asynchronously by its path\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds)\n * @param doNotTrackInParent - If false, tracks state in parent job (only use when fully awaiting the job)\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runFlowAsync(path: string | null, args: Record<string, any> | null, scheduledInSeconds: number | null = null, // can only be set to false if this the job will be fully await and not concurrent with any other job // as otherwise the child flow and its own child will store their state in the parent job which will // lead to incorrectness and failures doNotTrackInParent: boolean = true, tag: string | null = null): Promise<string>\n\n/**\n * Resolve a resource value in case the default value was picked because the input payload was undefined\n * @param obj resource value or path of the resource under the format `$res:path`\n * @returns resource value\n */\nasync resolveDefaultResource(obj: any): Promise<any>\n\n/**\n * Get the state file path from environment variables\n * @returns State path string\n */\ngetStatePath(): string\n\n/**\n * Set a resource value by path\n * @param path path of the resource to set, default to state path\n * @param value new value of the resource to set\n * @param initializeToTypeIfNotExist if the resource does not exist, initialize it with this type\n */\nasync setResource(value: any, path?: string, initializeToTypeIfNotExist?: string): Promise<void>\n\n/**\n * Set the state\n * @param state state to set\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync setState(state: any, path?: string): Promise<void>\n\n/**\n * Set the progress\n * Progress cannot go back and limited to 0% to 99% range\n * @param percent Progress to set in %\n * @param jobId? Job to set progress for\n */\nasync setProgress(percent: number, jobId?: any): Promise<void>\n\n/**\n * Get the progress\n * @param jobId? Job to get progress from\n * @returns Optional clamped between 0 and 100 progress value\n */\nasync getProgress(jobId?: any): Promise<number | null>\n\n/**\n * Whether the worker running this job has received its shutdown signal.\n * A draining worker waits for its current job to finish before exiting, so a\n * long-running script can poll this and return early to let the worker be replaced.\n * @param jobId? Job to check, defaults to the current job\n */\nasync workerIsDraining(jobId?: string): Promise<boolean>\n\n/**\n * Set a flow user state\n * @param key key of the state\n * @param value value of the state\n */\nasync setFlowUserState(key: string, value: any, errorIfNotPossible?: boolean): Promise<void>\n\n/**\n * Get a flow user state\n * @param path path of the variable\n */\nasync getFlowUserState(key: string, errorIfNotPossible?: boolean): Promise<any>\n\n/**\n * Get the state shared across executions\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync getState(path?: string): Promise<any>\n\n/**\n * Get a variable by path\n * @param path path of the variable\n * @returns variable value\n */\nasync getVariable(path: string): Promise<string>\n\n/**\n * Set a variable by path, create if not exist\n * @param path path of the variable\n * @param value value of the variable\n * @param isSecretIfNotExist if the variable does not exist, create it as secret or not (default: false)\n * @param descriptionIfNotExist if the variable does not exist, create it with this description (default: \"\")\n */\nasync setVariable(path: string, value: string, isSecretIfNotExist?: boolean, descriptionIfNotExist?: string): Promise<void>\n\n/**\n * Build a PostgreSQL connection URL from a database resource\n * @param path - Path to the database resource\n * @returns PostgreSQL connection URL string\n */\nasync databaseUrlFromResource(path: string): Promise<string>\n\nasync polarsConnectionSettings(s3_resource_path: string | undefined): Promise<any>\n\nasync duckdbConnectionSettings(s3_resource_path: string | undefined): Promise<any>\n\n/**\n * Get S3 client settings from a resource or workspace default\n * @param s3_resource_path - Path to S3 resource (uses workspace default if undefined)\n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n * @returns S3 client configuration settings\n */\nasync denoS3LightClientSettings(s3_resource_path: string | undefined, workspace: string | undefined = undefined): Promise<DenoS3LightClientSettings>\n\n/**\n * Load the content of a file stored in S3. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContent = await wmill.loadS3FileContent(inputFile)\n * // if the file is a raw text file, it can be decoded and printed directly:\n * const text = new TextDecoder().decode(fileContentStream)\n * console.log(text);\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3File(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise<Uint8Array | undefined>\n\n/**\n * Load the content of a file stored in S3 as a stream. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContentBlob = await wmill.loadS3FileStream(inputFile)\n * // if the content is plain text, the blob can be read directly:\n * console.log(await fileContentBlob.text());\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3FileStream(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise<Blob | undefined>\n\n/**\n * Persist a file to the S3 bucket. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * const s3object = await writeS3File(s3Object, \"Hello Windmill!\")\n * const fileContentAsUtf8Str = (await s3object.toArray()).toString('utf-8')\n * console.log(fileContentAsUtf8Str)\n * ```\n * \n * @param workspace - Workspace to write to (defaults to the `WM_WORKSPACE` env var)\n */\nasync writeS3File(s3object: S3Object | undefined, fileContent: string | Blob, s3ResourcePath: string | undefined = undefined, contentType: string | undefined = undefined, contentDisposition: string | undefined = undefined, workspace: string | undefined = undefined): Promise<S3Object>\n\n/**\n * Permanently delete a file from S3 by key.\n * \n * ```typescript\n * await wmill.deleteS3File({ s3: \"path/to/file.txt\" })\n * ```\n * \n * @param s3object - S3 object identifying the file to delete (must have `s3` set)\n * @param workspace - Workspace to delete from (defaults to the `WM_WORKSPACE` env var)\n */\nasync deleteS3File(s3object: S3Object, workspace: string | undefined = undefined): Promise<void>\n\n/**\n * Sign S3 objects to be used by anonymous users in public apps\n * @param s3objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 objects\n */\nasync signS3Objects(s3objects: S3Object[], { expirySecs }: { expirySecs?: number } = {}): Promise<S3Object[]>\n\n/**\n * Sign S3 object to be used by anonymous users in public apps\n * @param s3object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 object\n */\nasync signS3Object(s3object: S3Object, { expirySecs }: { expirySecs?: number } = {}): Promise<S3Object>\n\n/**\n * Generate a presigned public URL for an array of S3 objects.\n * If an S3 object is not signed yet, it will be signed first.\n * @param s3Objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns list of signed public URLs\n */\nasync getPresignedS3PublicUrls(s3Objects: S3Object[], { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise<string[]>\n\n/**\n * Generate a presigned public URL for an S3 object. If the S3 object is not signed yet, it will be signed first.\n * @param s3Object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed public URL\n */\nasync getPresignedS3PublicUrl(s3Objects: S3Object, { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise<string>\n\n/**\n * Get URLs needed for resuming a flow after this step\n * @param approver approver name\n * @param flowLevel if true, generate resume URLs for the parent flow instead of the specific step.\n * This allows pre-approvals that can be consumed by any later suspend step in the same flow.\n * @returns approval page UI URL, resume and cancel API URLs for resuming the flow\n */\nasync getResumeUrls(approver?: string, flowLevel?: boolean): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Get an OIDC jwt token for auth to external services (e.g: Vault, AWS) (ee only)\n * @param audience audience of the token\n * @param expiresIn Optional number of seconds until the token expires\n * @returns jwt token\n */\nasync getIdToken(audience: string, expiresIn?: number): Promise<string>\n\n/**\n * Convert a base64-encoded string to Uint8Array\n * @param data - Base64-encoded string\n * @returns Decoded Uint8Array\n */\nbase64ToUint8Array(data: string): Uint8Array\n\n/**\n * Convert a Uint8Array to base64-encoded string\n * @param arrayBuffer - Uint8Array to encode\n * @returns Base64-encoded string\n */\nuint8ArrayToBase64(arrayBuffer: Uint8Array): string\n\n/**\n * Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Slack approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Slack approval request.\n * @param {string} options.slackResourcePath - The path to the Slack resource in Windmill.\n * @param {string} options.channelId - The Slack channel ID where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Slack approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * @param {string} [options.resumeButtonText] - Optional text for the resume button.\n * @param {string} [options.cancelButtonText] - Optional text for the cancel button.\n * \n * @returns {Promise<void>} Resolves when the Slack approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getSlackApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveSlackApproval({\n * slackResourcePath: \"/u/alex/my_slack_resource\",\n * channelId: \"admins-slack-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * resumeButtonText: \"Resume\",\n * cancelButtonText: \"Cancel\",\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveSlackApproval({ slackResourcePath, channelId, message, approver, defaultArgsJson, dynamicEnumsJson, resumeButtonText, cancelButtonText, }: SlackApprovalOptions): Promise<void>\n\n/**\n * Sends an interactive approval request via Teams, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Teams approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Teams approval request.\n * @param {string} options.teamName - The Teams team name where the approval request will be sent.\n * @param {string} options.channelName - The Teams channel name where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Teams approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * \n * @returns {Promise<void>} Resolves when the Teams approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getTeamsApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveTeamsApproval({\n * teamName: \"admins-teams\",\n * channelName: \"admins-teams-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveTeamsApproval({ teamName, channelName, message, approver, defaultArgsJson, dynamicEnumsJson, }: TeamsApprovalOptions): Promise<void>\n\nsetWorkflowCtx(ctx: WorkflowCtx | null): void\n\nasync sleep(seconds: number): Promise<void>\n\n/**\n * Execute `fn` inline and checkpoint the result. On replay the cached value is\n * returned without re-executing `fn`.\n * \n * `fn`'s result is encoded as JSON and decoded back before it is returned, so\n * the round that runs the body sees the same types every replay sees: a `Date`\n * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape.\n * \n * Called from inside a task body, `fn` runs in place and nothing is\n * checkpointed: a task is a single job and is never replayed.\n */\nasync step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>>\n\n/**\n * Create a task that dispatches to a separate Windmill script.\n * \n * @example\n * const extract = taskScript(\"f/data/extract\");\n * // inside workflow: await extract({ url: \"https://...\" })\n */\ntaskScript(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike<any>\n\n/**\n * Create a task that dispatches to a separate Windmill flow.\n * \n * @example\n * const pipeline = taskFlow(\"f/etl/pipeline\");\n * // inside workflow: await pipeline({ input: data })\n */\ntaskFlow(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike<any>\n\n/**\n * Mark an async function as a workflow-as-code entry point.\n * \n * The function must be **deterministic**: given the same inputs it must call\n * tasks in the same order on every replay. Branching on task results is fine\n * (results are replayed from checkpoint), but branching on external state\n * (current time, random values, external API calls) must use `step()` to\n * checkpoint the value so replays see the same result.\n */\nworkflow<T>(fn: (...args: any[]) => Promise<T>): void\n\n/**\n * Suspend the workflow and wait for an external approval.\n * \n * Pass `key` to name the step, then `getApprovalUrls(key)` yields the URLs that\n * resume exactly this approval — route them through your own channel. Without a\n * key the steps are named `approval`, `approval_2`, ...\n * \n * `skin: \"minimal\"` shows approvers only the request (form and approve/reject)\n * instead of the detailed page with the workflow's details. `description` is\n * shown above the form: a string, or a rich value such as `{ markdown: \"...\" }`.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * const { value, approver } = await waitForApproval({ key: \"manager\", timeout: 3600 });\n */\nwaitForApproval(options?: { timeout?: number; form?: object; selfApproval?: boolean; key?: string; skin?: \"detailed\" | \"minimal\"; description?: string | object; }): PromiseLike<{ value: any; approver: string; approved: boolean }>\n\n/**\n * Resume/cancel/approval-page URLs bound to one `waitForApproval` step.\n * \n * Unlike `getResumeUrls()`, which signs a random nonce, these address the very\n * `resume_job` record the step's built-in approval buttons use, so they are\n * stable across replays and safe to embed in a custom notification.\n * \n * `stepKey` must match the `key` given to `waitForApproval`. Keys must be unique\n * within a workflow; reusing one throws rather than silently renaming it. The URL\n * only resumes while that step is awaiting approval; used at any other moment it is\n * rejected rather than banking a row a different approval would consume. Send it\n * ahead of time — approvers just cannot act before the workflow reaches the step.\n * \n * `resume` and `cancel` are step-bound; `approvalPage` is not — it opens the job's\n * approval page, which acts on whichever approval is pending when it is used.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * await waitForApproval({ key: \"manager\" });\n */\nasync getApprovalUrls(stepKey: string = \"approval\", approver?: string): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Process items in parallel with optional concurrency control.\n * \n * Each item is processed by calling `fn(item)`, which should be a task().\n * Items are dispatched in batches of `concurrency` (default: all at once).\n * \n * @example\n * const process = task(async (item: string) => { ... });\n * const results = await parallel(items, process, { concurrency: 5 });\n */\nasync parallel<T, R>(items: T[], fn: (item: T) => PromiseLike<R> | R, options?: { concurrency?: number },): Promise<R[]>\n\n/**\n * Commit Kafka offsets for a trigger with auto_commit disabled.\n * @param triggerPath - Path to the Kafka trigger (from event.wm_trigger.trigger_path)\n * @param topic - Kafka topic name (from event.topic)\n * @param partition - Partition number (from event.partition)\n * @param offset - Message offset to commit (from event.offset)\n */\nasync commitKafkaOffsets(triggerPath: string, topic: string, partition: number, offset: number,): Promise<void>\n\n/**\n * Parse an S3 object from URI string or record format\n * @param s3Object - S3 object as URI string (`s3://storage/key`, `s3:///key`\n * for the default storage) or record. Any other string throws rather than\n * falling back to an auto-generated key: an auto key is requested by\n * omitting the object, and a fallback would silently misplace the upload\n * on any typo.\n * @returns S3 object record with storage and s3 key\n */\nparseS3Object(s3Object: S3Object): S3ObjectRecord\n\n/**\n * Create a SQL template function for PostgreSQL/datatable queries\n * @param name - Database/datatable name (default: \"main\")\n * @param opts.role - Connect as this data table role instead of the data table's default one.\n * Only meaningful on a data table under roles, and only for a role you are a tenant of.\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.datatable()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}::int\n * `.fetch()\n * @example\n * // Read through a restricted role\n * let sql = wmill.datatable(\"main\", { role: \"analytics\" })\n */\ndatatable(name: string = \"main\", opts?: DatatableOptions): DatatableSqlTemplateFunction\n\n/**\n * Create a SQL template function for DuckDB/ducklake queries\n * @param name - DuckDB database name, optionally with a schema as `name:schema` (default: \"main\")\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.ducklake()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}\n * `.fetch()\n * @example\n * // Target a specific schema within the ducklake\n * let sql = wmill.ducklake(\"my_lake:analytics\")\n */\nducklake(name: string = \"main\"): SqlTemplateFunction\n\n/**\n * Idempotently materialize `selectSql` into a ducklake table for one\n * partition (or the whole table when `partition` is omitted) — the client-side\n * equivalent of the `// materialize` engine.\n * With `uniqueKey` it upserts the slice (delete-by-key + insert); otherwise it\n * replaces it (whole table → `CREATE OR REPLACE`; partition → delete + insert).\n * Safe to re-run for the same partition (backfill / failure-recovery).\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.upsertPartition({ table, selectSql, partition }).execute()`.\n */\nupsertPartition(opts: DucklakeMaterializeOptions): SqlStatement<any>\n\n/**\n * INSERT-only materialization (no dedup/replace) for append-only tables.\n * Re-running the same partition duplicates rows — use only for immutable\n * event-log sources.\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.appendPartition({ table, selectSql, partition }).execute()`.\n */\nappendPartition(opts: Omit<DucklakeMaterializeOptions, \"uniqueKey\">,): SqlStatement<any>\n", - "app.python3": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- 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.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) 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 the user each of its questions, 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.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- 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? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- 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.\n- The authoring reference below carries the Python SDK, for `python3` inline runnables. For a `bun` runnable, call `get_instructions` again with `subject: \"app\"` and no language.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- 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.\n- 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`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse 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.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe 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.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render(<App />)\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**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`.\n\n**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.\n\n**Read the page's context from `window.ctx`**: `ctx` is the viewer (absent for anonymous visitors), `workspace` and `path` the app's (`path` is not set under `wmill app dev`), and `query` the page URL's query parameters as strings (`…/apps/get/u/me/app?customer=42` gives `window.ctx.query.customer === '42'`, and no query gives `{}`). Read it there, not from `window.location`, which in a sandboxed app is not the page's address. It is read once when the app loads.\n\n**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.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode or a saved agent\n\nA 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.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@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.\n\n#### A saved agent: an `agent` runnable\n\nChat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not:\n\n```json\n{ \"chat\": { \"type\": \"agent\", \"path\": \"f/support/agent\" } }\n```\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\nimport * as wmill from './wmill'\n\nconst chat = useWindmillChat({ wmill, runnable: 'chat' })\n```\n\n`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message`; the chat passes the conversation id as `backendAsync.<key>(args, { memoryId })`: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.<key>({ user_message })`, it is a single run with no conversation, for a one-off question; `backend.<key>(args, { memoryId })` waits for the reply of a conversation turn. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of five types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn 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.\n\n#### The `wmill` client is already authenticated\n\nAn 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.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript / agent)\n\nWhen `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `previous_messages` when its memory is off.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew 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.\n\nInside 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.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA 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.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData 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.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **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.\n4. **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.\n5. **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`.\n6. **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.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`.\n\n\n# Python SDK (wmill)\n\nImport: import wmill\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe functions below are the surface to prefer. For an endpoint none of them covers,\nwmill.Windmill().get(endpoint) and .post(endpoint) issue an authenticated request against this\ninstance. What does not exist is a function name you guessed at: if it is not listed below, do\nnot call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`os.environ.get(\"WM_END_USER_EMAIL\") or os.environ.get(\"WM_EMAIL\")`. WM_END_USER_EMAIL is the app\nviewer when the run was triggered from an app and empty otherwise (both variables are always\ndefined), WM_EMAIL is the user the job is permissioned as. WM_USERNAME is the matching username.\n\ndef worker_has_internal_server() -> bool\n\ndef get_mocked_api() -> Optional[dict]\n\n# Get the HTTP client instance.\n# \n# Returns:\n# Configured httpx.Client for API requests\ndef get_client() -> httpx.Client\n\n# Make an HTTP GET request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.get\n# \n# Returns:\n# HTTP response object\ndef get(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Make an HTTP POST request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.post\n# \n# Returns:\n# HTTP response object\ndef post(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Create a new authentication token.\n# \n# Args:\n# duration: Token validity duration (default: 1 day)\n# \n# Returns:\n# New authentication token string\ndef create_token(duration = dt.timedelta(days=1)) -> str\n\n# Create a script job by path and return its job id.\n# \n# ``retry`` re-runs the job when it fails, with the policy a schedule takes,\n# e.g. ``{\"constant\": {\"attempts\": 3, \"seconds\": 10}}``. The returned id is\n# the first attempt's; each retry is a job of its own, recorded as a child of it.\ndef run_script_by_path_async(path: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a script job by hash and return its job id. See ``run_script_by_path_async`` for ``retry``.\ndef run_script_by_hash_async(hash_: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a flow job and return its job id.\ndef run_flow_async(path: str, args: dict = None, scheduled_in_secs: int = None, do_not_track_in_parent: bool = True, tag: str = None) -> str\n\n# Run script by path synchronously and return its result.\ndef run_script_by_path(path: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run script by hash synchronously and return its result.\ndef run_script_by_hash(hash_: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run a script on the current worker without creating a job.\n# \n# On agent workers (no internal server), falls back to running a normal\n# preview job and waiting for the result.\ndef run_inline_script_preview(content: str, language: str, args: dict = None) -> Any\n\n# Wait for a job to complete and return its result.\n# \n# Args:\n# job_id: ID of the job to wait for\n# timeout: Maximum time to wait (seconds or timedelta)\n# verbose: Enable verbose logging\n# cleanup: Register cleanup handler to cancel job on exit\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result when completed\n# \n# Raises:\n# TimeoutError: If timeout is reached\n# Exception: If job fails\ndef wait_job(job_id, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False)\n\n# Cancel a specific job by ID.\n# \n# Args:\n# job_id: UUID of the job to cancel\n# reason: Optional reason for cancellation\n# \n# Returns:\n# Response message from the cancel endpoint\ndef cancel_job(job_id: str, reason: str = None) -> str\n\n# Cancel currently running executions of the same script.\ndef cancel_running() -> dict\n\n# Get job details by ID.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job details dictionary\ndef get_job(job_id: str) -> dict\n\n# Get the root job ID for a flow hierarchy.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Root job ID\ndef get_root_job_id(job_id: str | None = None) -> dict\n\n# Get an OIDC JWT token for authentication to external services.\n# \n# Args:\n# audience: Token audience (e.g., \"vault\", \"aws\")\n# expires_in: Optional expiration time in seconds\n# \n# Returns:\n# JWT token string\ndef get_id_token(audience: str, expires_in: int | None = None) -> str\n\n# Get the status of a job.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job status: \"RUNNING\", \"WAITING\", or \"COMPLETED\"\ndef get_job_status(job_id: str) -> JobStatus\n\n# Get the result of a completed job.\n# \n# Args:\n# job_id: UUID of the completed job\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result\ndef get_result(job_id: str, assert_result_is_not_none: bool = True) -> Any\n\n# Get a variable value by path.\n# \n# Args:\n# path: Variable path in Windmill\n# \n# Returns:\n# Variable value as string\ndef get_variable(path: str) -> str\n\n# Set a variable value by path, creating it if it doesn't exist.\n# \n# Args:\n# path: Variable path in Windmill\n# value: Variable value to set\n# is_secret: Whether the variable should be secret (default: False)\ndef set_variable(path: str, value: str, is_secret: bool = False) -> None\n\n# Get a resource value by path.\n# \n# Args:\n# path: Resource path in Windmill\n# none_if_undefined: Return None instead of raising if not found\n# interpolated: if variables and resources are fully unrolled\n# \n# Returns:\n# Resource value dictionary or None\ndef get_resource(path: str, none_if_undefined: bool = False, interpolated: bool = True) -> dict | None\n\n# Set a resource value by path, creating it if it doesn't exist.\n# \n# Args:\n# value: Resource value to set\n# path: Resource path in Windmill\n# resource_type: Resource type for creation\ndef set_resource(value: Any, path: str, resource_type: str)\n\n# List resources from Windmill workspace.\n# \n# Args:\n# resource_type: Optional resource type to filter by (e.g., \"postgresql\", \"mysql\", \"s3\")\n# page: Optional page number for pagination\n# per_page: Optional number of results per page\n# \n# Returns:\n# List of resource dictionaries\ndef list_resources(resource_type: str = None, page: int = None, per_page: int = None) -> list[dict]\n\n# Set the workflow state.\n# \n# Args:\n# value: State value to set\n# path: Optional state resource path override.\ndef set_state(value: Any, path: str | None = None) -> None\n\n# Get the workflow state.\n# \n# Args:\n# path: Optional state resource path override.\n# \n# Returns:\n# State value or None if not set\ndef get_state(path: str | None = None) -> Any\n\n# Set job progress percentage (0-99).\n# \n# Args:\n# value: Progress percentage\n# job_id: Job ID (defaults to current WM_JOB_ID)\ndef set_progress(value: int, job_id: Optional[str] = None)\n\n# Get job progress percentage.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Progress value (0-100) or None if not set\ndef get_progress(job_id: Optional[str] = None) -> Any\n\n# Whether the worker running the job has received its shutdown signal.\n# \n# A draining worker waits for its current job to finish before exiting. A long-running\n# script can poll this and return early so the worker can be replaced.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# True if the worker running the job is draining\ndef worker_is_draining(job_id: Optional[str] = None) -> bool\n\n# Set the user state of a flow at a given key\ndef set_flow_user_state(key: str, value: Any) -> None\n\n# Get the user state of a flow at a given key\ndef get_flow_user_state(key: str) -> Any\n\n# Get the Windmill server version.\n# \n# Returns:\n# Version string\ndef version()\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: pass the storage's own bucket as ``Bucket``. The proxy\n# serves object reads, writes, deletes, listing and multipart uploads of that bucket only;\n# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials,\n# which passing the resource path returns.\ndef get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Load a file from the workspace s3 bucket and returns its content as bytes.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# my_obj_content = client.load_s3_file(s3_obj)\n# file_content = my_obj_content.decode(\"utf-8\")\n# '''\ndef load_s3_file(s3object: S3Object | str, s3_resource_path: str | None) -> bytes\n\n# Load a file from the workspace s3 bucket and returns the bytes stream.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# with wmill.load_s3_file_reader(s3object, s3_resource_path) as file_reader:\n# print(file_reader.read())\n# '''\ndef load_s3_file_reader(s3object: S3Object | str, s3_resource_path: str | None) -> BufferedReader\n\n# Write a file to the workspace S3 bucket\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# \n# # for an in memory bytes array:\n# file_content = b'Hello Windmill!'\n# client.write_s3_file(s3_obj, file_content)\n# \n# # for a file:\n# with open(\"my_file.txt\", \"rb\") as my_file:\n# client.write_s3_file(s3_obj, my_file)\n# '''\ndef write_s3_file(s3object: S3Object | str | None, file_content: BufferedReader | bytes, s3_resource_path: str | None, content_type: str | None = None, content_disposition: str | None = None) -> S3Object\n\n# Permanently delete a file from the workspace S3 bucket.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# client.delete_s3_object(s3_obj)\n# '''\ndef delete_s3_object(s3object: S3Object | str, s3_resource_path: str | None = None) -> None\n\n# Sign S3 objects for use by anonymous users in public apps.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed S3 objects\ndef sign_s3_objects(s3_objects: list[S3Object | str], expiry_secs: int | None = None) -> list[S3Object]\n\n# Sign a single S3 object for use by anonymous users in public apps.\n# \n# Args:\n# s3_object: S3 object to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed S3 object\ndef sign_s3_object(s3_object: S3Object | str, expiry_secs: int | None = None) -> S3Object\n\n# Generate presigned public URLs for an array of S3 objects.\n# If an S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# base_url: Optional base URL for the presigned URLs (defaults to WM_BASE_URL)\n# expiry_secs: How long the signatures stay valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed public URLs\n# \n# Example:\n# >>> s3_objs = [S3Object(s3=\"/path/to/file1.txt\"), S3Object(s3=\"/path/to/file2.txt\")]\n# >>> urls = client.get_presigned_s3_public_urls(s3_objs)\ndef get_presigned_s3_public_urls(s3_objects: list[S3Object | str], base_url: str | None = None, expiry_secs: int | None = None) -> list[str]\n\n# Generate a presigned public URL for an S3 object.\n# If the S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_object: S3 object to sign\n# base_url: Optional base URL for the presigned URL (defaults to WM_BASE_URL)\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed public URL\n# \n# Example:\n# >>> s3_obj = S3Object(s3=\"/path/to/file.txt\")\n# >>> url = client.get_presigned_s3_public_url(s3_obj)\ndef get_presigned_s3_public_url(s3_object: S3Object | str, base_url: str | None = None, expiry_secs: int | None = None) -> str\n\n# Get the current user information.\n# \n# Returns:\n# User details dictionary\ndef whoami() -> dict\n\n# Get the current user information (alias for whoami).\n# \n# Returns:\n# User details dictionary\ndef user() -> dict\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef state_path() -> str\n\n# Get the workflow state.\n# \n# Returns:\n# State value or None if not set\ndef state() -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state_pickle(value: Any, path: str = 'state.pickle') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state_pickle(path: str = 'state.pickle') -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state(value: Any, path: str = 'state.json') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state(path: str = 'state.json') -> None\n\n# Get URLs needed for resuming a flow after suspension.\n# \n# Args:\n# approver: Optional approver name\n# flow_level: If True, generate resume URLs for the parent flow instead of the\n# specific step. This allows pre-approvals that can be consumed by any later\n# suspend step in the same flow.\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_resume_urls(approver: str = None, flow_level: bool = None) -> dict\n\n# Get the resume URLs bound to one ``wait_for_approval`` step of this workflow.\n# \n# Args:\n# step_key: Checkpoint key of the approval step, as passed to\n# ``wait_for_approval(key=...)``\n# approver: Optional approver name\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_approval_urls(step_key: str = 'approval', approver: str = None) -> dict\n\n# Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n# \n# **[Enterprise Edition Only]** To include form fields in the Slack approval request, use the \"Advanced -> Suspend -> Form\" functionality.\n# Learn more at: https://www.windmill.dev/docs/flows/flow_approval#form\n# \n# :param slack_resource_path: The path to the Slack resource in Windmill.\n# :type slack_resource_path: str\n# :param channel_id: The Slack channel ID where the approval request will be sent.\n# :type channel_id: str\n# :param message: Optional custom message to include in the Slack approval request.\n# :type message: str, optional\n# :param approver: Optional user ID or name of the approver for the request.\n# :type approver: str, optional\n# :param default_args_json: Optional dictionary defining or overriding the default arguments for form fields.\n# :type default_args_json: dict, optional\n# :param dynamic_enums_json: Optional dictionary overriding the enum default values of enum form fields.\n# :type dynamic_enums_json: dict, optional\n# \n# :raises Exception: If the function is not called within a flow or flow preview.\n# :raises Exception: If the required flow job or flow step environment variables are not set.\n# \n# :return: None\n# \n# **Usage Example:**\n# >>> client.request_interactive_slack_approval(\n# ... slack_resource_path=\"/u/alex/my_slack_resource\",\n# ... channel_id=\"admins-slack-channel\",\n# ... message=\"Please approve this request\",\n# ... approver=\"approver123\",\n# ... default_args_json={\"key1\": \"value1\", \"key2\": 42},\n# ... dynamic_enums_json={\"foo\": [\"choice1\", \"choice2\"], \"bar\": [\"optionA\", \"optionB\"]},\n# ... )\n# \n# **Notes:**\n# - This function must be executed within a Windmill flow or flow preview.\n# - The function checks for required environment variables (`WM_FLOW_JOB_ID`, `WM_FLOW_STEP_ID`) to ensure it is run in the appropriate context.\ndef request_interactive_slack_approval(slack_resource_path: str, channel_id: str, message: str = None, approver: str = None, default_args_json: dict = None, dynamic_enums_json: dict = None) -> None\n\n# Send a message to a Microsoft Teams conversation with conversation_id, where success is used to style the message\ndef send_teams_message(conversation_id: str, text: str, success: bool = True, card_block: dict = None)\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# Only meaningful on a data table under roles, and only for a role you are a\n# tenant of.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None)\n\n# Get a DuckLake client for DuckDB queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# \n# Returns:\n# DucklakeClient instance\ndef ducklake(name: str = 'main')\n\ndef init_global_client(f)\n\ndef deprecate(in_favor_of: str)\n\n# Get the current workspace ID.\n# \n# Returns:\n# Workspace ID string\ndef get_workspace() -> str\n\ndef get_version() -> str\n\n# Create a script job and return its job ID.\n# \n# Args:\n# hash_or_path: Script hash or path (determined by presence of '/')\n# args: Script arguments\n# scheduled_in_secs: Delay before execution in seconds\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Job ID string\ndef run_script_async(hash_or_path: str, args: Dict[str, Any] = None, scheduled_in_secs: int = None, tag: str = None) -> str\n\n# Run a script synchronously by hash and return its result.\n# \n# Args:\n# hash: Script hash\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_sync(hash: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Run a script synchronously by path and return its result.\n# \n# Args:\n# path: Script path\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_by_path_sync(path: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB\ndef duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars\ndef polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3\ndef boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef get_state_path() -> str\n\n# Parse resource syntax from string.\ndef parse_resource_syntax(s: str) -> Optional[str]\n\n# Parse S3 object from a `s3://<storage>/<key>` URI string (`s3:///<key>`\n# for the default storage) or S3Object format. Any other string raises\n# rather than falling back to an auto-generated key: an auto key is\n# requested by omitting the object, and a fallback would silently misplace\n# the upload on any typo.\ndef parse_s3_object(s3_object: S3Object | str) -> S3Object\n\n# Parse variable syntax from string.\ndef parse_variable_syntax(s: str) -> Optional[str]\n\n# Append a text to the result stream.\n# \n# Args:\n# text: text to append to the result stream\ndef append_to_result_stream(text: str) -> None\n\n# Stream to the result stream.\n# \n# Args:\n# stream: stream to stream to the result stream\ndef stream_result(stream) -> None\n\n# Execute a SQL query against the DataTable.\n# \n# Args:\n# sql: SQL query string with $1, $2, etc. placeholders\n# *args: Positional arguments to bind to query placeholders\n# \n# Returns:\n# SqlQuery instance for fetching results\ndef query(sql: str, *args) -> SqlQuery\n\n# Idempotently materialize the rows of `select_sql` into ducklake\n# `table` for one `partition` (or the whole table when `partition` is\n# None). Client-side equivalent of the `// materialize` engine: with\n# `unique_key` it upserts within the slice (delete-by-key + insert);\n# without it, it replaces (whole table → CREATE OR REPLACE; partition →\n# delete the partition + insert). Re-running the same slice is safe — the\n# backfill / failure-recovery contract.\n# \n# The partition value is bound as a DuckDB arg (never string-interpolated)\n# so it cannot inject SQL. `select_sql` is trusted (your own query).\ndef upsert_partition(table: str, select_sql: str, partition: str = None, unique_key: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# INSERT-only materialization (no dedup / no replace) for an immutable\n# event-log table — for one `partition`, or the whole table when\n# `partition` is None. NOTE: unlike `upsert_partition`, re-running the same\n# slice duplicates rows — use only for append-only sources.\ndef append_partition(table: str, select_sql: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Read a materialized ducklake table, optionally a single partition.\ndef read(table: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Execute query and fetch results.\n# \n# Args:\n# result_collection: Optional result collection mode\n# \n# Returns:\n# Query results\ndef fetch(result_collection: str | None = None)\n\n# Execute query and fetch first row of results.\n# \n# Returns:\n# First row of query results\ndef fetch_one()\n\n# Execute query and fetch first row of results. Return result as a scalar value.\n# \n# Returns:\n# First row of query result as a scalar value\ndef fetch_one_scalar()\n\n# Execute query and don't return any results.\n# \ndef execute()\n\n# DuckDB executor requires explicit argument types at declaration\n# These types exist in both DuckDB and Postgres\n# Check that the types exist if you plan to extend this function for other SQL engines.\ndef infer_sql_type(value) -> str\n\ndef parse_sql_client_name(name: str) -> tuple[str, Optional[str]]\n\n# Decorator that marks a function as a workflow task.\n# \n# Works in both WAC v1 (sync, HTTP-based dispatch) and WAC v2\n# (async, checkpoint/replay) modes:\n# \n# - **v2 (inside @workflow)**: dispatches as a checkpoint step.\n# - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API.\n# - **Standalone, or called from inside another v2 task**: executes the\n# function body directly. A task runs as a single job, so the tasks it\n# calls run in that same job, without their own options.\n# \n# A task runs as its own job, so its result is always encoded as JSON and\n# decoded back before the caller sees it: a ``datetime`` comes back as a\n# string, a tuple as a list.\n# \n# ``retry`` re-dispatches the task after a failure, inside ``@workflow`` only.\n# Every attempt is a step of its own (``call_api``, ``call_api#2``, ...) and\n# the wait between two of them is a durable sleep, so a retrying task holds no\n# worker while it backs off. Keys: ``attempts`` (retries after the first\n# failure, a whole number from 0 to 100), ``delay`` (seconds before the first\n# retry, sub-second delays dropped), ``multiplier`` (applied to the delay\n# after each attempt, 1 keeps it constant), ``max_delay`` (ceiling in\n# seconds). ``attempts`` is required, and an out-of-range or unknown key is\n# rejected where the policy is written.\n# \n# A workflow sleeps once per round, so tasks backing off in the same fan-out\n# wait one after another rather than together: the delay before a fan-out\n# retries is the sum of every backoff pending in it, not the longest one, and\n# it grows with both the width of the fan-out and ``attempts``. Retries with\n# no ``delay`` all go out in a single round.\n# \n# ``cache_ttl`` serves a previous result of the task for that many seconds\n# instead of running it again. A task is keyed on its step key (its name and\n# call order) and the workflow's input, not on the arguments it is called\n# with, so cache one only when whether it runs, and what it receives, follow\n# from the workflow's input alone. A ``task_script`` target is keyed on the\n# arguments it is called with. It has no effect on a ``task_flow`` target,\n# which keeps its flow's own cache policy.\n# \n# Usage::\n# \n# @task\n# async def extract_data(url: str): ...\n# \n# @task(path=\"f/external_script\", timeout=600, tag=\"gpu\")\n# async def run_external(x: int): ...\n# \n# @task(retry={\"attempts\": 3, \"delay\": 30, \"multiplier\": 2})\n# async def call_api(payload: dict): ...\ndef task(_func = None, *, path: Optional[str] = None, tag: Optional[str] = None, timeout: Optional[int] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill script.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# extract = task_script(\"f/data/extract\", timeout=600)\n# \n# @workflow\n# async def main():\n# data = await extract(url=\"https://...\")\ndef task_script(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill flow.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# pipeline = task_flow(\"f/etl/pipeline\", priority=10)\n# \n# @workflow\n# async def main():\n# result = await pipeline(input=data)\ndef task_flow(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Decorator marking an async function as a workflow-as-code entry point.\n# \n# The function must be **deterministic**: given the same inputs it must call\n# tasks in the same order on every replay. Branching on task results is fine\n# (results are replayed from checkpoint), but branching on external state\n# (current time, random values, external API calls) must use ``step()`` to\n# checkpoint the value so replays see the same result.\ndef workflow(func)\n\n# Execute ``fn`` inline and checkpoint the result.\n# \n# On replay the cached value is returned without re-executing ``fn``.\n# Use for lightweight deterministic operations (timestamps, random IDs,\n# config reads) that should not incur the overhead of a child job.\n# \n# ``fn``'s result is encoded as JSON and decoded back before it is returned,\n# so the round that runs the body sees the same types every replay sees:\n# a ``datetime`` comes back as a string, a tuple as a list.\n# \n# Called from inside a task body, ``fn`` runs in place and nothing is\n# checkpointed: a task is a single job and is never replayed.\nasync def step(name: str, fn)\n\n# Server-side sleep — suspend the workflow for the given duration without holding a worker.\n# \n# Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``.\n# Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``.\nasync def sleep(seconds: int)\n\n# Suspend the workflow and wait for an external approval.\n# \n# Pass ``key`` to name the step, then ``get_approval_urls(key)`` yields the URLs\n# that resume exactly this approval — route them through your own channel.\n# Without a key the steps are named ``approval``, ``approval_2``, ...\n# \n# Returns a dict with ``value`` (form data), ``approver``, and ``approved``.\n# \n# Args:\n# timeout: Approval timeout in seconds (default 1800).\n# form: Optional form schema for the approval page.\n# self_approval: Whether the user who triggered the flow can approve it (default True).\n# key: Optional checkpoint key naming this approval step.\n# skin: ``\"minimal\"`` shows approvers only the request (form and approve/reject)\n# instead of the detailed page with the workflow's details.\n# description: Shown to approvers above the form: a string, or a rich value such as\n# ``{\"markdown\": \"...\"}``.\n# \n# Example::\n# \n# urls = await step(\"urls\", lambda: get_approval_urls(\"manager\"))\n# await step(\"notify\", lambda: send_email(urls[\"resume\"], urls[\"cancel\"]))\n# result = await wait_for_approval(key=\"manager\", timeout=3600)\nasync def wait_for_approval(timeout: int = 1800, form: dict | None = None, self_approval: bool = True, key: str | None = None, skin: Literal['detailed', 'minimal'] | None = None, description: str | dict | None = None) -> dict\n\n# Process items in parallel with optional concurrency control.\n# \n# Each item is processed by calling ``fn(item)``, which should be a @task.\n# Items are dispatched in batches of ``concurrency`` (default: all at once).\n# \n# Example::\n# \n# @task\n# async def process(item: str):\n# ...\n# \n# results = await parallel(items, process, concurrency=5)\nasync def parallel(items, fn, *, concurrency: Optional[int] = None)\n\n# Commit Kafka offsets for a trigger with auto_commit disabled.\n# \n# Args:\n# trigger_path: Path to the Kafka trigger (from event['wm_trigger']['trigger_path'])\n# topic: Kafka topic name (from event['topic'])\n# partition: Partition number (from event['partition'])\n# offset: Message offset to commit (from event['offset'])\ndef commit_kafka_offsets(trigger_path: str, topic: str, partition: int, offset: int) -> None\n\n", + "app": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- 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.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) 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 the user each of its questions, 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.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- 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? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- 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.\n- The authoring reference below carries the TypeScript SDK. For a `python3` runnable, call `get_instructions` again with `subject: \"app\"` and `language: \"python3\"`.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- 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.\n- 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`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse 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.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe 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.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render(<App />)\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**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`.\n\n**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.\n\n**Read the page's context from `window.ctx`**: `ctx` is the viewer (absent for anonymous visitors), `workspace` and `path` the app's (`path` is not set under `wmill app dev`), and `query` the page URL's query parameters as strings (`…/apps/get/u/me/app?customer=42` gives `window.ctx.query.customer === '42'`, and no query gives `{}`). Read it there, not from `window.location`, which in a sandboxed app is not the page's address. It is read once when the app loads.\n\n**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.\n\n### Styling\n\nPlain CSS imported from the entrypoint (`import './index.css'`) is bundled as is. For **Tailwind CSS v4**, add `tailwindcss` (`^4`) to `package.json` and start `index.css` with `@import \"tailwindcss\";`: the bundler then compiles it, generating the utilities used in the app's files and in the workspace's shared `/ui` folder, along with `@theme`, `@utility`, `@apply` and `@custom-variant`. A design system's stylesheet can live in `/ui` and be imported with `@import \"/ui/theme.css\";`. There is no `tailwind.config.js`: configure Tailwind in CSS. `@plugin` and `@config` are compiled only by the CLI (`wmill app bundle` / `wmill app push`), not by the web editor, and `wmill app dev` must be restarted to pick up an edit to one of them or to a file they import. Without the `tailwindcss` dependency, Tailwind directives are left uncompiled.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode or a saved agent\n\nA 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.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@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.\n\n#### A saved agent: an `agent` runnable\n\nChat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not:\n\n```json\n{ \"chat\": { \"type\": \"agent\", \"path\": \"f/support/agent\" } }\n```\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\nimport * as wmill from './wmill'\n\nconst chat = useWindmillChat({ wmill, runnable: 'chat' })\n```\n\n`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message`; the chat passes the conversation id as `backendAsync.<key>(args, { memoryId })`: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.<key>({ user_message })`, it is a single run with no conversation, for a one-off question; `backend.<key>(args, { memoryId })` waits for the reply of a conversation turn. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of five types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn 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.\n\n#### The `wmill` client is already authenticated\n\nAn 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.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript / agent)\n\nWhen `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `previous_messages` when its memory is off.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew 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.\n\nInside 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.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA 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.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData 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.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **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.\n4. **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.\n5. **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`.\n6. **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.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`.\n\n\n# TypeScript SDK (windmill-client)\n\nImport: import * as wmill from 'windmill-client'\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe helpers below are the surface to prefer. For an endpoint none of them covers, import the\ngenerated service classes (JobService, ScriptService, ...) from 'windmill-client' — they are not\nlisted here but they do exist. What does not exist is a helper name you guessed at: if it is\nneither listed below nor a service method, do not call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`process.env.WM_END_USER_EMAIL || process.env.WM_EMAIL`. WM_END_USER_EMAIL is the app viewer when\nthe run was triggered from an app and empty otherwise (both variables are always defined), WM_EMAIL\nis the user the job is permissioned as. WM_USERNAME is the matching username.\n\nworkerHasInternalServer(): boolean\n\n/**\n * Initialize the Windmill client with authentication token and base URL\n * @param token - Authentication token (defaults to WM_TOKEN env variable)\n * @param baseUrl - API base URL (defaults to BASE_INTERNAL_URL or BASE_URL env variable)\n */\nsetClient(token?: string, baseUrl?: string): void\n\n/**\n * Create a client configuration from env variables\n * @returns client configuration\n */\ngetWorkspace(): string\n\n/**\n * Get a resource value by path\n * @param path path of the resource, default to internal state path\n * @param undefinedIfEmpty if the resource does not exist, return undefined instead of throwing an error\n * @returns resource value\n */\nasync getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>\n\n/**\n * Get the true root job id\n * @param jobId job id to get the root job id from (default to current job)\n * @returns root job id\n */\nasync getRootJobId(jobId?: string): Promise<string>\n\n/**\n * Run a script synchronously by its path and wait for the result\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByPath(path: string, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Run a script synchronously by its hash and wait for the result\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Script execution result\n */\nasync runScriptByHash(hash_: string, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Append a text to the result stream\n * @param text text to append to the result stream\n */\nappendToResultStream(text: string): void\n\n/**\n * Stream to the result stream\n * @param stream stream to stream to the result stream\n */\nasync streamResult(stream: AsyncIterable<string>): Promise<void>\n\n/**\n * Run a flow synchronously by its path and wait for the result\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param verbose - Enable verbose logging\n * @param tag - Override the worker tag the job runs on\n * @returns Flow execution result\n */\nasync runFlow(path: string | null = null, args: Record<string, any> | null = null, verbose: boolean = false, tag: string | null = null): Promise<any>\n\n/**\n * Wait for a job to complete and return its result\n * @param jobId - ID of the job to wait for\n * @param verbose - Enable verbose logging\n * @returns Job result when completed\n */\nasync waitJob(jobId: string, verbose: boolean = false): Promise<any>\n\n/**\n * Get the result of a completed job\n * @param jobId - ID of the completed job\n * @returns Job result\n */\nasync getResult(jobId: string): Promise<any>\n\n/**\n * Get the result of a job if completed, or its current status\n * @param jobId - ID of the job\n * @returns Object with started, completed, success, and result properties\n */\nasync getResultMaybe(jobId: string): Promise<any>\n\n/**\n * Cancel a queued or running job by ID.\n * @param jobId - UUID of the job to cancel\n * @param reason - Optional reason for cancellation\n * @returns Response message from the cancel endpoint\n */\nasync cancelJob(jobId: string, reason: string | undefined = undefined): Promise<string>\n\n/**\n * Run a script asynchronously by its path\n * @param path - Script path in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByPathAsync(path: string, args: Record<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\n\n/**\n * Run a script asynchronously by its hash\n * @param hash_ - Script hash in Windmill\n * @param args - Arguments to pass to the script\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds), or {@link RunScriptAsyncOptions}\n * `{ scheduledInSeconds?, tag?, retry? }`, e.g. `{ retry: { constant: { attempts: 3, seconds: 10 } } }`\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runScriptByHashAsync(hash_: string, args: Record<string, any> | null = null, scheduledInSeconds: number | null | RunScriptAsyncOptions = null, tag: string | null = null): Promise<string>\n\n/**\n * Run a flow asynchronously by its path\n * @param path - Flow path in Windmill\n * @param args - Arguments to pass to the flow\n * @param scheduledInSeconds - Schedule execution for a future time (in seconds)\n * @param doNotTrackInParent - If false, tracks state in parent job (only use when fully awaiting the job)\n * @param tag - Override the worker tag the job runs on\n * @returns Job ID of the created job\n */\nasync runFlowAsync(path: string | null, args: Record<string, any> | null, scheduledInSeconds: number | null = null, // can only be set to false if this the job will be fully await and not concurrent with any other job // as otherwise the child flow and its own child will store their state in the parent job which will // lead to incorrectness and failures doNotTrackInParent: boolean = true, tag: string | null = null): Promise<string>\n\n/**\n * Resolve a resource value in case the default value was picked because the input payload was undefined\n * @param obj resource value or path of the resource under the format `$res:path`\n * @returns resource value\n */\nasync resolveDefaultResource(obj: any): Promise<any>\n\n/**\n * Get the state file path from environment variables\n * @returns State path string\n */\ngetStatePath(): string\n\n/**\n * Set a resource value by path\n * @param path path of the resource to set, default to state path\n * @param value new value of the resource to set\n * @param initializeToTypeIfNotExist if the resource does not exist, initialize it with this type\n */\nasync setResource(value: any, path?: string, initializeToTypeIfNotExist?: string): Promise<void>\n\n/**\n * Set the state\n * @param state state to set\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync setState(state: any, path?: string): Promise<void>\n\n/**\n * Set the progress\n * Progress cannot go back and limited to 0% to 99% range\n * @param percent Progress to set in %\n * @param jobId? Job to set progress for\n */\nasync setProgress(percent: number, jobId?: any): Promise<void>\n\n/**\n * Get the progress\n * @param jobId? Job to get progress from\n * @returns Optional clamped between 0 and 100 progress value\n */\nasync getProgress(jobId?: any): Promise<number | null>\n\n/**\n * Whether the worker running this job has received its shutdown signal.\n * A draining worker waits for its current job to finish before exiting, so a\n * long-running script can poll this and return early to let the worker be replaced.\n * @param jobId? Job to check, defaults to the current job\n */\nasync workerIsDraining(jobId?: string): Promise<boolean>\n\n/**\n * Set a flow user state\n * @param key key of the state\n * @param value value of the state\n */\nasync setFlowUserState(key: string, value: any, errorIfNotPossible?: boolean): Promise<void>\n\n/**\n * Get a flow user state\n * @param path path of the variable\n */\nasync getFlowUserState(key: string, errorIfNotPossible?: boolean): Promise<any>\n\n/**\n * Get the state shared across executions\n * @param path Optional state resource path override. Defaults to `getStatePath()`.\n */\nasync getState(path?: string): Promise<any>\n\n/**\n * Get a variable by path\n * @param path path of the variable\n * @returns variable value\n */\nasync getVariable(path: string): Promise<string>\n\n/**\n * Set a variable by path, create if not exist\n * @param path path of the variable\n * @param value value of the variable\n * @param isSecretIfNotExist if the variable does not exist, create it as secret or not (default: false)\n * @param descriptionIfNotExist if the variable does not exist, create it with this description (default: \"\")\n */\nasync setVariable(path: string, value: string, isSecretIfNotExist?: boolean, descriptionIfNotExist?: string): Promise<void>\n\n/**\n * Build a PostgreSQL connection URL from a database resource\n * @param path - Path to the database resource\n * @returns PostgreSQL connection URL string\n */\nasync databaseUrlFromResource(path: string): Promise<string>\n\nasync polarsConnectionSettings(s3_resource_path: string | undefined): Promise<any>\n\nasync duckdbConnectionSettings(s3_resource_path: string | undefined): Promise<any>\n\n/**\n * Get S3 client settings from a resource or workspace default\n * @param s3_resource_path - Path to S3 resource (uses workspace default if undefined)\n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n * @returns S3 client configuration settings\n */\nasync denoS3LightClientSettings(s3_resource_path: string | undefined, workspace: string | undefined = undefined): Promise<DenoS3LightClientSettings>\n\n/**\n * Load the content of a file stored in S3. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContent = await wmill.loadS3FileContent(inputFile)\n * // if the file is a raw text file, it can be decoded and printed directly:\n * const text = new TextDecoder().decode(fileContentStream)\n * console.log(text);\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3File(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise<Uint8Array | undefined>\n\n/**\n * Load the content of a file stored in S3 as a stream. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * let fileContentBlob = await wmill.loadS3FileStream(inputFile)\n * // if the content is plain text, the blob can be read directly:\n * console.log(await fileContentBlob.text());\n * ```\n * \n * @param workspace - Workspace to read from (defaults to the `WM_WORKSPACE` env var)\n */\nasync loadS3FileStream(s3object: S3Object, s3ResourcePath: string | undefined = undefined, workspace: string | undefined = undefined): Promise<Blob | undefined>\n\n/**\n * Persist a file to the S3 bucket. If the s3ResourcePath is undefined, it will default to the workspace S3 resource.\n * \n * ```typescript\n * const s3object = await writeS3File(s3Object, \"Hello Windmill!\")\n * const fileContentAsUtf8Str = (await s3object.toArray()).toString('utf-8')\n * console.log(fileContentAsUtf8Str)\n * ```\n * \n * @param workspace - Workspace to write to (defaults to the `WM_WORKSPACE` env var)\n */\nasync writeS3File(s3object: S3Object | undefined, fileContent: string | Blob, s3ResourcePath: string | undefined = undefined, contentType: string | undefined = undefined, contentDisposition: string | undefined = undefined, workspace: string | undefined = undefined): Promise<S3Object>\n\n/**\n * Permanently delete a file from S3 by key.\n * \n * ```typescript\n * await wmill.deleteS3File({ s3: \"path/to/file.txt\" })\n * ```\n * \n * @param s3object - S3 object identifying the file to delete (must have `s3` set)\n * @param workspace - Workspace to delete from (defaults to the `WM_WORKSPACE` env var)\n */\nasync deleteS3File(s3object: S3Object, workspace: string | undefined = undefined): Promise<void>\n\n/**\n * Sign S3 objects to be used by anonymous users in public apps\n * @param s3objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 objects\n */\nasync signS3Objects(s3objects: S3Object[], { expirySecs }: { expirySecs?: number } = {}): Promise<S3Object[]>\n\n/**\n * Sign S3 object to be used by anonymous users in public apps\n * @param s3object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed s3 object\n */\nasync signS3Object(s3object: S3Object, { expirySecs }: { expirySecs?: number } = {}): Promise<S3Object>\n\n/**\n * Generate a presigned public URL for an array of S3 objects.\n * If an S3 object is not signed yet, it will be signed first.\n * @param s3Objects s3 objects to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns list of signed public URLs\n */\nasync getPresignedS3PublicUrls(s3Objects: S3Object[], { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise<string[]>\n\n/**\n * Generate a presigned public URL for an S3 object. If the S3 object is not signed yet, it will be signed first.\n * @param s3Object s3 object to sign\n * @param expirySecs how long the signature stays valid, in seconds (default 43200 = 12h, clamped to [60, 604800])\n * @returns signed public URL\n */\nasync getPresignedS3PublicUrl(s3Objects: S3Object, { baseUrl, expirySecs }: { baseUrl?: string; expirySecs?: number } = {}): Promise<string>\n\n/**\n * Get URLs needed for resuming a flow after this step\n * @param approver approver name\n * @param flowLevel if true, generate resume URLs for the parent flow instead of the specific step.\n * This allows pre-approvals that can be consumed by any later suspend step in the same flow.\n * @returns approval page UI URL, resume and cancel API URLs for resuming the flow\n */\nasync getResumeUrls(approver?: string, flowLevel?: boolean): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Get an OIDC jwt token for auth to external services (e.g: Vault, AWS) (ee only)\n * @param audience audience of the token\n * @param expiresIn Optional number of seconds until the token expires\n * @returns jwt token\n */\nasync getIdToken(audience: string, expiresIn?: number): Promise<string>\n\n/**\n * Convert a base64-encoded string to Uint8Array\n * @param data - Base64-encoded string\n * @returns Decoded Uint8Array\n */\nbase64ToUint8Array(data: string): Uint8Array\n\n/**\n * Convert a Uint8Array to base64-encoded string\n * @param arrayBuffer - Uint8Array to encode\n * @returns Base64-encoded string\n */\nuint8ArrayToBase64(arrayBuffer: Uint8Array): string\n\n/**\n * Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Slack approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Slack approval request.\n * @param {string} options.slackResourcePath - The path to the Slack resource in Windmill.\n * @param {string} options.channelId - The Slack channel ID where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Slack approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * @param {string} [options.resumeButtonText] - Optional text for the resume button.\n * @param {string} [options.cancelButtonText] - Optional text for the cancel button.\n * \n * @returns {Promise<void>} Resolves when the Slack approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getSlackApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveSlackApproval({\n * slackResourcePath: \"/u/alex/my_slack_resource\",\n * channelId: \"admins-slack-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * resumeButtonText: \"Resume\",\n * cancelButtonText: \"Cancel\",\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveSlackApproval({ slackResourcePath, channelId, message, approver, defaultArgsJson, dynamicEnumsJson, resumeButtonText, cancelButtonText, }: SlackApprovalOptions): Promise<void>\n\n/**\n * Sends an interactive approval request via Teams, allowing optional customization of the message, approver, and form fields.\n * \n * **[Enterprise Edition Only]** To include form fields in the Teams approval request, go to **Advanced -> Suspend -> Form**\n * and define a form. Learn more at [Windmill Documentation](https://www.windmill.dev/docs/flows/flow_approval#form).\n * \n * @param {Object} options - The configuration options for the Teams approval request.\n * @param {string} options.teamName - The Teams team name where the approval request will be sent.\n * @param {string} options.channelName - The Teams channel name where the approval request will be sent.\n * @param {string} [options.message] - Optional custom message to include in the Teams approval request.\n * @param {string} [options.approver] - Optional user ID or name of the approver for the request.\n * @param {DefaultArgs} [options.defaultArgsJson] - Optional object defining or overriding the default arguments to a form field.\n * @param {Enums} [options.dynamicEnumsJson] - Optional object overriding the enum default values of an enum form field.\n * \n * @returns {Promise<void>} Resolves when the Teams approval request is successfully sent.\n * \n * @throws {Error} If the function is not called within a flow or flow preview.\n * @throws {Error} If the `JobService.getTeamsApprovalPayload` call fails.\n * \n * **Usage Example:**\n * ```typescript\n * await requestInteractiveTeamsApproval({\n * teamName: \"admins-teams\",\n * channelName: \"admins-teams-channel\",\n * message: \"Please approve this request\",\n * approver: \"approver123\",\n * defaultArgsJson: { key1: \"value1\", key2: 42 },\n * dynamicEnumsJson: { foo: [\"choice1\", \"choice2\"], bar: [\"optionA\", \"optionB\"] },\n * });\n * ```\n * \n * **Note:** This function requires execution within a Windmill flow or flow preview.\n */\nasync requestInteractiveTeamsApproval({ teamName, channelName, message, approver, defaultArgsJson, dynamicEnumsJson, }: TeamsApprovalOptions): Promise<void>\n\nsetWorkflowCtx(ctx: WorkflowCtx | null): void\n\nasync sleep(seconds: number): Promise<void>\n\n/**\n * Execute `fn` inline and checkpoint the result. On replay the cached value is\n * returned without re-executing `fn`.\n * \n * `fn`'s result is encoded as JSON and decoded back before it is returned, so\n * the round that runs the body sees the same types every replay sees: a `Date`\n * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape.\n * \n * Called from inside a task body, `fn` runs in place and nothing is\n * checkpointed: a task is a single job and is never replayed.\n */\nasync step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>>\n\n/**\n * Create a task that dispatches to a separate Windmill script.\n * \n * @example\n * const extract = taskScript(\"f/data/extract\");\n * // inside workflow: await extract({ url: \"https://...\" })\n */\ntaskScript(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike<any>\n\n/**\n * Create a task that dispatches to a separate Windmill flow.\n * \n * @example\n * const pipeline = taskFlow(\"f/etl/pipeline\");\n * // inside workflow: await pipeline({ input: data })\n */\ntaskFlow(path: string, options?: TaskOptions): (...args: any[]) => PromiseLike<any>\n\n/**\n * Mark an async function as a workflow-as-code entry point.\n * \n * The function must be **deterministic**: given the same inputs it must call\n * tasks in the same order on every replay. Branching on task results is fine\n * (results are replayed from checkpoint), but branching on external state\n * (current time, random values, external API calls) must use `step()` to\n * checkpoint the value so replays see the same result.\n */\nworkflow<T>(fn: (...args: any[]) => Promise<T>): void\n\n/**\n * Suspend the workflow and wait for an external approval.\n * \n * Pass `key` to name the step, then `getApprovalUrls(key)` yields the URLs that\n * resume exactly this approval — route them through your own channel. Without a\n * key the steps are named `approval`, `approval_2`, ...\n * \n * `skin: \"minimal\"` shows approvers only the request (form and approve/reject)\n * instead of the detailed page with the workflow's details. `description` is\n * shown above the form: a string, or a rich value such as `{ markdown: \"...\" }`.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * const { value, approver } = await waitForApproval({ key: \"manager\", timeout: 3600 });\n */\nwaitForApproval(options?: { timeout?: number; form?: object; selfApproval?: boolean; key?: string; skin?: \"detailed\" | \"minimal\"; description?: string | object; }): PromiseLike<{ value: any; approver: string; approved: boolean }>\n\n/**\n * Resume/cancel/approval-page URLs bound to one `waitForApproval` step.\n * \n * Unlike `getResumeUrls()`, which signs a random nonce, these address the very\n * `resume_job` record the step's built-in approval buttons use, so they are\n * stable across replays and safe to embed in a custom notification.\n * \n * `stepKey` must match the `key` given to `waitForApproval`. Keys must be unique\n * within a workflow; reusing one throws rather than silently renaming it. The URL\n * only resumes while that step is awaiting approval; used at any other moment it is\n * rejected rather than banking a row a different approval would consume. Send it\n * ahead of time — approvers just cannot act before the workflow reaches the step.\n * \n * `resume` and `cancel` are step-bound; `approvalPage` is not — it opens the job's\n * approval page, which acts on whichever approval is pending when it is used.\n * \n * @example\n * const urls = await step(\"urls\", () => getApprovalUrls(\"manager\"));\n * await step(\"notify\", () => sendEmail(urls.resume, urls.cancel));\n * await waitForApproval({ key: \"manager\" });\n */\nasync getApprovalUrls(stepKey: string = \"approval\", approver?: string): Promise<{\n approvalPage: string;\n resume: string;\n cancel: string;\n}>\n\n/**\n * Process items in parallel with optional concurrency control.\n * \n * Each item is processed by calling `fn(item)`, which should be a task().\n * Items are dispatched in batches of `concurrency` (default: all at once).\n * \n * @example\n * const process = task(async (item: string) => { ... });\n * const results = await parallel(items, process, { concurrency: 5 });\n */\nasync parallel<T, R>(items: T[], fn: (item: T) => PromiseLike<R> | R, options?: { concurrency?: number },): Promise<R[]>\n\n/**\n * Commit Kafka offsets for a trigger with auto_commit disabled.\n * @param triggerPath - Path to the Kafka trigger (from event.wm_trigger.trigger_path)\n * @param topic - Kafka topic name (from event.topic)\n * @param partition - Partition number (from event.partition)\n * @param offset - Message offset to commit (from event.offset)\n */\nasync commitKafkaOffsets(triggerPath: string, topic: string, partition: number, offset: number,): Promise<void>\n\n/**\n * Parse an S3 object from URI string or record format\n * @param s3Object - S3 object as URI string (`s3://storage/key`, `s3:///key`\n * for the default storage) or record. Any other string throws rather than\n * falling back to an auto-generated key: an auto key is requested by\n * omitting the object, and a fallback would silently misplace the upload\n * on any typo.\n * @returns S3 object record with storage and s3 key\n */\nparseS3Object(s3Object: S3Object): S3ObjectRecord\n\n/**\n * Create a SQL template function for PostgreSQL/datatable queries\n * @param name - Database/datatable name (default: \"main\")\n * @param opts.role - Connect as this data table role instead of the data table's default one.\n * Only meaningful on a data table under roles, and only for a role you are a tenant of.\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.datatable()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}::int\n * `.fetch()\n * @example\n * // Read through a restricted role\n * let sql = wmill.datatable(\"main\", { role: \"analytics\" })\n */\ndatatable(name: string = \"main\", opts?: DatatableOptions): DatatableSqlTemplateFunction\n\n/**\n * Create a SQL template function for DuckDB/ducklake queries\n * @param name - DuckDB database name, optionally with a schema as `name:schema` (default: \"main\")\n * @returns SQL template function for building parameterized queries\n * @example\n * let sql = wmill.ducklake()\n * let name = 'Robin'\n * let age = 21\n * await sql`\n * SELECT * FROM friends\n * WHERE name = ${name} AND age = ${age}\n * `.fetch()\n * @example\n * // Target a specific schema within the ducklake\n * let sql = wmill.ducklake(\"my_lake:analytics\")\n */\nducklake(name: string = \"main\"): SqlTemplateFunction\n\n/**\n * Idempotently materialize `selectSql` into a ducklake table for one\n * partition (or the whole table when `partition` is omitted) — the client-side\n * equivalent of the `// materialize` engine.\n * With `uniqueKey` it upserts the slice (delete-by-key + insert); otherwise it\n * replaces it (whole table → `CREATE OR REPLACE`; partition → delete + insert).\n * Safe to re-run for the same partition (backfill / failure-recovery).\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.upsertPartition({ table, selectSql, partition }).execute()`.\n */\nupsertPartition(opts: DucklakeMaterializeOptions): SqlStatement<any>\n\n/**\n * INSERT-only materialization (no dedup/replace) for append-only tables.\n * Re-running the same partition duplicates rows — use only for immutable\n * event-log sources.\n * \n * Returns a lazy statement — call `.execute()` to run it:\n * `await wmill.appendPartition({ table, selectSql, partition }).execute()`.\n */\nappendPartition(opts: Omit<DucklakeMaterializeOptions, \"uniqueKey\">,): SqlStatement<any>\n", + "app.python3": "# Global draft app instructions\n\n- Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy.\n- 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.\n- To create a new app, use `init_app` with a path, optional summary, a framework (`react19` / `react18` / `svelte5`) 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 the user each of its questions, 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.\n- `init_app` seeds the starter inline runnables `greet`, `word_stats`, `slow_task`, `stream_text` so the demo tour works on first render. Replace or remove them once you start building real backend runnables.\n- Frontend file paths start with `/` (e.g. `/index.tsx`, `/App.tsx`, `/styles.css`). Use `write_app_file` / `patch_app_file` / `delete_app_file`.\n- 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? }`).\n- `/wmill.d.ts` (or `wmill.ts`) is generated automatically from the backend runnables — never write it directly.\n- Inline runnables only support `bun` or `python3` in chat. Path runnables (`script`/`flow`/`hubscript`) reference an existing item.\n- 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.\n- The authoring reference below carries the Python SDK, for `python3` inline runnables. For a `bun` runnable, call `get_instructions` again with `subject: \"app\"` and no language.\n- Use `deploy_workspace_item` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app.\n- 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.\n- 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`).\n\n# Windmill raw app authoring reference\n\n# Windmill Raw Apps\n\nRaw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables.\n\n## App shape\n\nA raw app has three logical parts:\n\n- **Frontend** — bundled with esbuild from `index.tsx` as the entrypoint. Files include the entrypoint, components (`App.tsx`), styles, etc.\n- **Backend runnables** — server-side scripts the frontend calls, each addressed by a unique key.\n- **Data** — optional whitelisted datatables (managed PostgreSQL) that the backend runnables can query. The frontend never queries the database directly; backend runnables are the only bridge.\n\n## Starting a new app\n\nA new app gets the setup Windmill's own new-app dialog gives one: a framework, then where its data lives.\n\n### Framework\n\nUse 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.\n\n### Data setup\n\nWhen a new app has to store data and the user did not say where, **ask before creating anything**: no app, no schema, no table. Where the data lives is the user's decision, and tables created in the wrong place stay there. Look up the workspace's data tables first so every choice you offer exists, then ask, as proposed answers rather than open questions:\n\n1. **Data table**: which one to use, the default first (`main` when it exists, otherwise the first listed). Skip this one when the workspace has a single data table.\n2. **Schema**: where the app's new tables go.\n - A **new schema**, the usual choice, offered first. Suggest the first unused name among `app1`, `app2`, …\n - An **existing schema** of that data table, by name.\n - **None**: the tables go in `public`.\n3. **Tables**: only when that data table already holds tables the app could use, whether to **reuse** them (name them) or **create new ones**.\n\nDo not ask when:\n\n- the user already said where the data goes. A part they left out takes its default above: the default data table, a new `appN` schema, new tables;\n- the app, or its saved draft, already carries a data config (`data.datatable`, `data.schema` or `data.tables`). That config is the answer;\n- the app stores nothing.\n\nWith no data table in the workspace there is nothing to choose: say that one has to be configured in the workspace settings before the app can store data.\n\nA question left unanswered or dismissed is not a go-ahead for the defaults: stop there and say what is still needed.\n\nThen build what was chosen: the data table and schema become the app's `data.datatable` and `data.schema`, the tables it uses, reused or new, go in `data.tables`, and a new schema is created (`CREATE SCHEMA IF NOT EXISTS`) before the tables that go in it.\n\n### An app that arrives already set up\n\nAn app the user just started from the new-app dialog is already set up: its files are the framework template it was started with, and a `data` config it carries (`data.datatable`, `data.schema` or `data.tables`) is the data setup it was started with. Build that app in place, with that data config, and in that framework unless the user now names another. Do not ask for either, and do not create a second app. Only when it carries no data config and has to store data is the data setup still to ask.\n\n## Frontend\n\n### Entrypoint\n\nThe 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.\n\nReact (`index.tsx`):\n\n```tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport App from './App'\n\ncreateRoot(document.getElementById('root')!).render(<App />)\n```\n\nSvelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`.\n\n**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`.\n\n**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.\n\n**Read the page's context from `window.ctx`**: `ctx` is the viewer (absent for anonymous visitors), `workspace` and `path` the app's (`path` is not set under `wmill app dev`), and `query` the page URL's query parameters as strings (`…/apps/get/u/me/app?customer=42` gives `window.ctx.query.customer === '42'`, and no query gives `{}`). Read it there, not from `window.location`, which in a sandboxed app is not the page's address. It is read once when the app loads.\n\n**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.\n\n### Styling\n\nPlain CSS imported from the entrypoint (`import './index.css'`) is bundled as is. For **Tailwind CSS v4**, add `tailwindcss` (`^4`) to `package.json` and start `index.css` with `@import \"tailwindcss\";`: the bundler then compiles it, generating the utilities used in the app's files and in the workspace's shared `/ui` folder, along with `@theme`, `@utility`, `@apply` and `@custom-variant`. A design system's stylesheet can live in `/ui` and be imported with `@import \"/ui/theme.css\";`. There is no `tailwind.config.js`: configure Tailwind in CSS. `@plugin` and `@config` are compiled only by the CLI (`wmill app bundle` / `wmill app push`), not by the web editor, and `wmill app dev` must be restarted to pick up an edit to one of them or to a file they import. Without the `tailwindcss` dependency, Tailwind directives are left uncompiled.\n\n### Generated bindings (`wmill.d.ts` / `wmill.ts`)\n\nThe frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten.\n\n### Calling backend runnables\n\nImport the generated bindings and call the runnable like a function. `./wmill` is the **only** way the frontend reaches anything server-side — datatables, workspace items, external services. Never `fetch` the Windmill API from frontend code: the bundle holds no token and builds no API URL.\n\n| Export | Resolves to | Use it for |\n|---|---|---|\n| `backend.<key>(args)` | the runnable's result | the default — run and wait |\n| `backendAsync.<key>(args)` | the **job id** (a string) | long-running work you want to track |\n| `waitJob(jobId)` | the job's **result** (rejects if the job failed) | awaiting a `backendAsync` job |\n| `getJob(jobId)` | a `Job` (`{ type, success, result, duration_ms, ... }`) | polling status without blocking |\n| `streamJob(jobId, onUpdate?)` | the final result, calling `onUpdate` per chunk | showing output as it is produced |\n\nA runnable is always called with **one object** whose keys are its `main` parameters — `main(user_id: string, limit: number)` is called as `backend.get_users({ user_id, limit })`, never with positional arguments. A runnable without parameters is called with no argument. Resource and variable ids handed to the `wmill` client are paths (`u/<user>/<name>` or `f/<folder>/<name>`).\n\nRun and wait — the common case:\n\n```tsx\nimport { backend } from './wmill';\n\nconst user = await backend.get_user({ user_id: '123' });\n```\n\nStart a long job, then await it:\n\n```tsx\nimport { backendAsync, waitJob } from './wmill';\n\nconst jobId = await backendAsync.run_report({ month: '2026-08' }); // a string\nconst report = await waitJob(jobId); // the result itself\n```\n\nOr poll it without blocking, to render progress:\n\n```tsx\nimport { getJob } from './wmill';\n\nconst job = await getJob(jobId);\nif (job.type === 'CompletedJob') setReport(job.result);\n```\n\n`backendAsync` resolves a job id and nothing else — guard on it before storing or polling. A poll loop started on an `undefined` id never completes and shows as a row stuck \"running\" forever:\n\n```tsx\nconst jobId = await backendAsync.run_report(args);\nif (!jobId) throw new Error('run_report did not start a job');\n```\n\n**Never hand-write a job-polling runnable.** A backend runnable that calls `jobs/list`, or that returns `getResultMaybe(...)` for the frontend to poll, reimplements `backendAsync` + `waitJob` / `getJob` / `streamJob` — and it is what leads to guessing at base URLs and tokens.\n\n### Keeping data out of recorded demos\n\nAn app can be demoed by recording a session: every interaction becomes a step carrying a snapshot of the page, replayed publicly or on the Hub. Password inputs are masked automatically. Mark anything else that must not appear with `data-wm-no-record` — the whole marked subtree is dropped from every snapshot, along with its values and the step's own metadata:\n\n```tsx\n<label data-wm-no-record>\n Customer SSN <input value={ssn} onChange={onSsn} />\n</label>\n```\n\nApply it to customer data, internal notes and anything else a viewer of the demo should not see. It costs nothing when the app is never recorded.\n\n### Chat UIs over a flow in chat mode or a saved agent\n\nA 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.\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\n\nconst chat = useWindmillChat({ flowPath: 'f/support/assistant' })\n// chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop()\n```\n\n`@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.\n\n#### A saved agent: an `agent` runnable\n\nChat with a saved AI agent (an `ai_agent` resource) through an `agent` runnable, a path runnable whose `path` is the agent's. Each call runs one turn of the agent's chat as the app, so a sandboxed app declares no frontend SDK scope, viewers get no consent prompt and need no access to the agent. Prefer it in every app, sandboxed or not:\n\n```json\n{ \"chat\": { \"type\": \"agent\", \"path\": \"f/support/agent\" } }\n```\n\n```tsx\nimport { useWindmillChat } from '@windmill-labs/chat-sdk/react'\nimport * as wmill from './wmill'\n\nconst chat = useWindmillChat({ wmill, runnable: 'chat' })\n```\n\n`runnable` is the runnable's key; each runnable keeps its own conversations. The runnable takes `user_message`; the chat passes the conversation id as `backendAsync.<key>(args, { memoryId })`: the agent remembers earlier turns of a conversation, and a signed-in viewer's conversations are theirs alone. Called directly as `backend.<key>({ user_message })`, it is a single run with no conversation, for a one-off question; `backend.<key>(args, { memoryId })` waits for the reply of a conversation turn. The chat needs an agent with managed memory. An agent whose memory is off keeps none: its runnable takes `previous_messages` (chat messages) instead, and the app keeps the history itself. The chat keeps its transcript in the app's own storage. `chat.stop()` stops following without cancelling the turn, and a message sent while it still runs is refused with `TurnRunningError`. Attachments are not supported this way.\n\n## Backend runnables\n\nEach runnable has a unique key (used to call it from the frontend) and one of five types:\n\n| Type | What it is |\n|---|---|\n| `inline` | Custom code stored on the app itself. Most common for app-specific logic. |\n| `script` | Reference to an existing workspace script by path. |\n| `flow` | Reference to an existing workspace flow by path. |\n| `hubscript` | Reference to a hub script by path. |\n| `agent` | Reference to a saved AI agent by path. Each call is one turn of its chat (see the chat section above). |\n\n### Inline runnables\n\nInline runnables carry their own source code, and must expose a `main` function as their entrypoint.\n\n**TypeScript example** (runnable `get_user`):\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable();\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n return user;\n}\n```\n\n**Python example** (runnable `get_user`):\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable()\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n return user\n```\n\n#### Sharing code between runnables\n\nAn 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.\n\n#### The `wmill` client is already authenticated\n\nAn 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.\n\n**Don't read `WM_TOKEN` or `BASE_INTERNAL_URL` and build an API URL to `fetch`.** The client's own `setClient` already reads exactly those, and it also sets the credentials mode a raw app needs (`WM_RAW_APP` suppresses credentials, because a sandboxed bundle calls the API from an opaque origin that can never pair with `Access-Control-Allow-Origin: *`). Rebuilding that by hand drops the parts you can't see. Use `wmill.*` for everything Windmill, and `fetch` only for third-party APIs.\n\nUse only `wmill` functions the SDK actually exports; for an endpoint none of them covers, the generated service classes (`JobService`, `ScriptService`, ...) are importable from `windmill-client`. What is not available is a name you guessed at: `getBaseUrl` and `getWorkspaceToken` are inventions, not API.\n\n### Path runnables (script / flow / hubscript / agent)\n\nWhen `type` is `script`, `flow`, `hubscript` or `agent`, the runnable just stores a `path` to an existing workspace or hub item — no inline code. The referenced item's input/output schema becomes the runnable's surface; an agent's is `user_message` and `user_attachments`, plus `previous_messages` when its memory is off.\n\nBefore writing an inline runnable, look for a workspace script or flow that already does the job, or a Hub script (a prebuilt integration at `hub/<version>/<app>/<name>`) for a third-party service, and reference it instead of copying its logic.\n\n### Draft code vs deployed code\n\nThis decides whether an app works before anything is deployed:\n\n- **Inline runnables run the app's current code.** The editor sends the runnable's source with each request, so an inline runnable works in the preview with nothing deployed.\n- **Path runnables (`script` / `flow` / `hubscript` / `agent`) run the DEPLOYED item at that path.** So do `wmill.runFlow`, `wmill.runFlowAsync` and `wmill.runScriptByPath` called from inside a runnable. A draft — including a draft you just created — does not exist for them.\n\nSo an app wired to a flow you just wrote does nothing until **that flow is deployed**. The app itself does NOT have to be deployed for this: the preview runs the app's draft, so the referenced flow is the only thing that has to exist deployed.\n\nThat makes the fix a one-item deploy, not a release. Offer to deploy exactly the referenced flow or script and leave the app a draft the user keeps testing in the preview — do not push the whole change set through the review-and-deploy page, and do not ask the user to deploy the app, unless they said they want to ship it.\n\nDo NOT quietly reimplement the flow inside an inline runnable to dodge the deployment: that leaves the user with two copies of the same logic and an app that ignores the flow they asked for. Inline the logic only when the user actually wants it inline.\n\nPrefer a **path runnable of type `flow`** over an inline runnable that calls `wmill.runFlowAsync`. The path runnable gives the frontend the flow's real input schema and works with `backend` / `backendAsync` / `waitJob` like any other runnable; a hand-written wrapper gives up all of that.\n\n### Static inputs\n\n`staticInputs` is an optional `Record<string, any>` for arguments not overridable from the frontend. Useful with path runnables to pre-fill some args while leaving the rest to the frontend caller.\n\n## Who can open a deployed app\n\nA draft app is reachable by nobody; deploying is what exposes it, and its backend runnables with it. Otherwise only users with access to the app can open it, unless the app is opened to:\n\n- **anonymous** users: anyone with the URL, without logging in;\n- **guests**: anyone the instance's identity provider authenticates, whether or not they belong to the workspace.\n\nEither one lets those people run the app's backend runnables, so never open an app up unless the user asks.\nWhen a deploy widens who may open the app, tell the user in plain words.\n\n## Sandbox isolation and frontend API access\n\nNew 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.\n\nInside 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.\nYou cannot turn isolation off; the user does it in the app's deploy settings.\n\n## Reading data as the viewer\n\nA 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.\nSet it with `viewerDataAccess: true` on the backend runnable.\n\n## Data Tables\n\nData 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.\n\n### Critical rules\n\n1. **Check what exists first**: look up the workspace's data tables and their tables before designing storage, and reuse a suitable table rather than creating another. Never assume a `main` data table exists.\n2. **Whitelisted tables only**: a runnable can only query tables listed in the app's `data.tables` config. Queries against unlisted tables fail at runtime, so register a new table there before using it.\n3. **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.\n4. **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.\n5. **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`.\n6. **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.\n\n### Querying in TypeScript (Bun/Deno)\n\n```typescript\nimport * as wmill from 'windmill-client';\n\nexport async function main(user_id: string) {\n const sql = wmill.datatable(); // Or: wmill.datatable('other_datatable')\n\n // Parameterized queries (safe from SQL injection)\n const user = await sql`SELECT * FROM users WHERE id = ${user_id}`.fetchOne();\n const users = await sql`SELECT * FROM users WHERE active = ${true}`.fetch();\n\n // Insert/Update\n await sql`INSERT INTO users (name, email) VALUES (${name}, ${email})`.execute();\n await sql`UPDATE users SET name = ${newName} WHERE id = ${user_id}`.execute();\n\n return user;\n}\n```\n\n### Querying in Python\n\n```python\nimport wmill\n\ndef main(user_id: str):\n db = wmill.datatable() # Or: wmill.datatable('other_datatable')\n\n # Use $1, $2, etc. for parameters\n user = db.query('SELECT * FROM users WHERE id = $1', user_id).fetch_one()\n users = db.query('SELECT * FROM users WHERE active = $1', True).fetch()\n\n # Insert/Update\n db.query('INSERT INTO users (name, email) VALUES ($1, $2)', name, email).execute()\n db.query('UPDATE users SET name = $1 WHERE id = $2', new_name, user_id).execute()\n\n return user\n```\n\n## Best Practices\n\n1. **Check existing tables** before creating new ones — reuse beats schema growth.\n2. **Use parameterized queries** — never concatenate user input into SQL.\n3. **Terminate every datatable statement** — the tagged template and `db.query(...)` only build a statement. It runs when you call `fetch` / `fetchOne` / `fetchOneScalar` / `execute` (`fetch` / `fetch_one` / `fetch_one_scalar` / `execute` in Python). An INSERT or UPDATE without one writes nothing and raises nothing. Awaiting the statement itself is a no-op — it is not a promise.\n4. **Keep runnables focused** — one function per runnable; small surface area.\n5. **Use descriptive keys** — `get_user`, not `a`.\n6. **Always whitelist tables** — adding a runnable that queries a new table requires the table to be in `data.tables` first.\n7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you.\n8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable.\n9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying.\n10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow or a saved agent** — never hand-roll a runnable that runs it and polls its stream; a saved agent is an `agent` runnable passed as `{ wmill, runnable }`.\n\n\n# Python SDK (wmill)\n\nImport: import wmill\n\nThe client configures itself from the job's environment — base URL, token and credentials mode\nare all set before your code runs, so there is nothing to initialize and no reason to read\nWM_TOKEN or BASE_INTERNAL_URL and build an API URL yourself. Reconstructing that by hand only\nreintroduces details the client already handles. Call the SDK for anything Windmill, and use raw\nHTTP for third-party APIs.\n\nThe functions below are the surface to prefer. For an endpoint none of them covers,\nwmill.Windmill().get(endpoint) and .post(endpoint) issue an authenticated request against this\ninstance. What does not exist is a function name you guessed at: if it is not listed below, do\nnot call it.\n\nTo know who is running the script, read the contextual variables rather than calling the API:\n`os.environ.get(\"WM_END_USER_EMAIL\") or os.environ.get(\"WM_EMAIL\")`. WM_END_USER_EMAIL is the app\nviewer when the run was triggered from an app and empty otherwise (both variables are always\ndefined), WM_EMAIL is the user the job is permissioned as. WM_USERNAME is the matching username.\n\ndef worker_has_internal_server() -> bool\n\ndef get_mocked_api() -> Optional[dict]\n\n# Get the HTTP client instance.\n# \n# Returns:\n# Configured httpx.Client for API requests\ndef get_client() -> httpx.Client\n\n# Make an HTTP GET request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.get\n# \n# Returns:\n# HTTP response object\ndef get(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Make an HTTP POST request to the Windmill API.\n# \n# Args:\n# endpoint: API endpoint path\n# raise_for_status: Whether to raise an exception on HTTP errors\n# **kwargs: Additional arguments passed to httpx.post\n# \n# Returns:\n# HTTP response object\ndef post(endpoint, raise_for_status = True, **kwargs) -> httpx.Response\n\n# Create a new authentication token.\n# \n# Args:\n# duration: Token validity duration (default: 1 day)\n# \n# Returns:\n# New authentication token string\ndef create_token(duration = dt.timedelta(days=1)) -> str\n\n# Create a script job by path and return its job id.\n# \n# ``retry`` re-runs the job when it fails, with the policy a schedule takes,\n# e.g. ``{\"constant\": {\"attempts\": 3, \"seconds\": 10}}``. The returned id is\n# the first attempt's; each retry is a job of its own, recorded as a child of it.\ndef run_script_by_path_async(path: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a script job by hash and return its job id. See ``run_script_by_path_async`` for ``retry``.\ndef run_script_by_hash_async(hash_: str, args: dict = None, scheduled_in_secs: int = None, tag: str = None, retry: dict = None) -> str\n\n# Create a flow job and return its job id.\ndef run_flow_async(path: str, args: dict = None, scheduled_in_secs: int = None, do_not_track_in_parent: bool = True, tag: str = None) -> str\n\n# Run script by path synchronously and return its result.\ndef run_script_by_path(path: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run script by hash synchronously and return its result.\ndef run_script_by_hash(hash_: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any\n\n# Run a script on the current worker without creating a job.\n# \n# On agent workers (no internal server), falls back to running a normal\n# preview job and waiting for the result.\ndef run_inline_script_preview(content: str, language: str, args: dict = None) -> Any\n\n# Wait for a job to complete and return its result.\n# \n# Args:\n# job_id: ID of the job to wait for\n# timeout: Maximum time to wait (seconds or timedelta)\n# verbose: Enable verbose logging\n# cleanup: Register cleanup handler to cancel job on exit\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result when completed\n# \n# Raises:\n# TimeoutError: If timeout is reached\n# Exception: If job fails\ndef wait_job(job_id, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False)\n\n# Cancel a specific job by ID.\n# \n# Args:\n# job_id: UUID of the job to cancel\n# reason: Optional reason for cancellation\n# \n# Returns:\n# Response message from the cancel endpoint\ndef cancel_job(job_id: str, reason: str = None) -> str\n\n# Cancel currently running executions of the same script.\ndef cancel_running() -> dict\n\n# Get job details by ID.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job details dictionary\ndef get_job(job_id: str) -> dict\n\n# Get the root job ID for a flow hierarchy.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Root job ID\ndef get_root_job_id(job_id: str | None = None) -> dict\n\n# Get an OIDC JWT token for authentication to external services.\n# \n# Args:\n# audience: Token audience (e.g., \"vault\", \"aws\")\n# expires_in: Optional expiration time in seconds\n# \n# Returns:\n# JWT token string\ndef get_id_token(audience: str, expires_in: int | None = None) -> str\n\n# Get the status of a job.\n# \n# Args:\n# job_id: UUID of the job\n# \n# Returns:\n# Job status: \"RUNNING\", \"WAITING\", or \"COMPLETED\"\ndef get_job_status(job_id: str) -> JobStatus\n\n# Get the result of a completed job.\n# \n# Args:\n# job_id: UUID of the completed job\n# assert_result_is_not_none: Raise exception if result is None\n# \n# Returns:\n# Job result\ndef get_result(job_id: str, assert_result_is_not_none: bool = True) -> Any\n\n# Get a variable value by path.\n# \n# Args:\n# path: Variable path in Windmill\n# \n# Returns:\n# Variable value as string\ndef get_variable(path: str) -> str\n\n# Set a variable value by path, creating it if it doesn't exist.\n# \n# Args:\n# path: Variable path in Windmill\n# value: Variable value to set\n# is_secret: Whether the variable should be secret (default: False)\ndef set_variable(path: str, value: str, is_secret: bool = False) -> None\n\n# Get a resource value by path.\n# \n# Args:\n# path: Resource path in Windmill\n# none_if_undefined: Return None instead of raising if not found\n# interpolated: if variables and resources are fully unrolled\n# \n# Returns:\n# Resource value dictionary or None\ndef get_resource(path: str, none_if_undefined: bool = False, interpolated: bool = True) -> dict | None\n\n# Set a resource value by path, creating it if it doesn't exist.\n# \n# Args:\n# value: Resource value to set\n# path: Resource path in Windmill\n# resource_type: Resource type for creation\ndef set_resource(value: Any, path: str, resource_type: str)\n\n# List resources from Windmill workspace.\n# \n# Args:\n# resource_type: Optional resource type to filter by (e.g., \"postgresql\", \"mysql\", \"s3\")\n# page: Optional page number for pagination\n# per_page: Optional number of results per page\n# \n# Returns:\n# List of resource dictionaries\ndef list_resources(resource_type: str = None, page: int = None, per_page: int = None) -> list[dict]\n\n# Set the workflow state.\n# \n# Args:\n# value: State value to set\n# path: Optional state resource path override.\ndef set_state(value: Any, path: str | None = None) -> None\n\n# Get the workflow state.\n# \n# Args:\n# path: Optional state resource path override.\n# \n# Returns:\n# State value or None if not set\ndef get_state(path: str | None = None) -> Any\n\n# Set job progress percentage (0-99).\n# \n# Args:\n# value: Progress percentage\n# job_id: Job ID (defaults to current WM_JOB_ID)\ndef set_progress(value: int, job_id: Optional[str] = None)\n\n# Get job progress percentage.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# Progress value (0-100) or None if not set\ndef get_progress(job_id: Optional[str] = None) -> Any\n\n# Whether the worker running the job has received its shutdown signal.\n# \n# A draining worker waits for its current job to finish before exiting. A long-running\n# script can poll this and return early so the worker can be replaced.\n# \n# Args:\n# job_id: Job ID (defaults to current WM_JOB_ID)\n# \n# Returns:\n# True if the worker running the job is draining\ndef worker_is_draining(job_id: Optional[str] = None) -> bool\n\n# Set the user state of a flow at a given key\ndef set_flow_user_state(key: str, value: Any) -> None\n\n# Get the user state of a flow at a given key\ndef get_flow_user_state(key: str) -> Any\n\n# Get the Windmill server version.\n# \n# Returns:\n# Version string\ndef version()\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the\n# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with\n# the storage's own credentials instead.\ndef get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3.\n# \n# Without a resource path, the connection goes to the workspace storage through Windmill's\n# S3 proxy when that storage is S3: pass the storage's own bucket as ``Bucket``. The proxy\n# serves object reads, writes, deletes, listing and multipart uploads of that bucket only;\n# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials,\n# which passing the resource path returns.\ndef get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Load a file from the workspace s3 bucket and returns its content as bytes.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# my_obj_content = client.load_s3_file(s3_obj)\n# file_content = my_obj_content.decode(\"utf-8\")\n# '''\ndef load_s3_file(s3object: S3Object | str, s3_resource_path: str | None) -> bytes\n\n# Load a file from the workspace s3 bucket and returns the bytes stream.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# with wmill.load_s3_file_reader(s3object, s3_resource_path) as file_reader:\n# print(file_reader.read())\n# '''\ndef load_s3_file_reader(s3object: S3Object | str, s3_resource_path: str | None) -> BufferedReader\n\n# Write a file to the workspace S3 bucket\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# \n# # for an in memory bytes array:\n# file_content = b'Hello Windmill!'\n# client.write_s3_file(s3_obj, file_content)\n# \n# # for a file:\n# with open(\"my_file.txt\", \"rb\") as my_file:\n# client.write_s3_file(s3_obj, my_file)\n# '''\ndef write_s3_file(s3object: S3Object | str | None, file_content: BufferedReader | bytes, s3_resource_path: str | None, content_type: str | None = None, content_disposition: str | None = None) -> S3Object\n\n# Permanently delete a file from the workspace S3 bucket.\n# \n# '''python\n# from wmill import S3Object\n# \n# s3_obj = S3Object(s3=\"/path/to/my_file.txt\")\n# client.delete_s3_object(s3_obj)\n# '''\ndef delete_s3_object(s3object: S3Object | str, s3_resource_path: str | None = None) -> None\n\n# Sign S3 objects for use by anonymous users in public apps.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed S3 objects\ndef sign_s3_objects(s3_objects: list[S3Object | str], expiry_secs: int | None = None) -> list[S3Object]\n\n# Sign a single S3 object for use by anonymous users in public apps.\n# \n# Args:\n# s3_object: S3 object to sign\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed S3 object\ndef sign_s3_object(s3_object: S3Object | str, expiry_secs: int | None = None) -> S3Object\n\n# Generate presigned public URLs for an array of S3 objects.\n# If an S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_objects: List of S3 objects to sign\n# base_url: Optional base URL for the presigned URLs (defaults to WM_BASE_URL)\n# expiry_secs: How long the signatures stay valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# List of signed public URLs\n# \n# Example:\n# >>> s3_objs = [S3Object(s3=\"/path/to/file1.txt\"), S3Object(s3=\"/path/to/file2.txt\")]\n# >>> urls = client.get_presigned_s3_public_urls(s3_objs)\ndef get_presigned_s3_public_urls(s3_objects: list[S3Object | str], base_url: str | None = None, expiry_secs: int | None = None) -> list[str]\n\n# Generate a presigned public URL for an S3 object.\n# If the S3 object is not signed yet, it will be signed first.\n# \n# Args:\n# s3_object: S3 object to sign\n# base_url: Optional base URL for the presigned URL (defaults to WM_BASE_URL)\n# expiry_secs: How long the signature stays valid, in seconds\n# (defaults to 43200 = 12h, clamped to [60, 604800])\n# \n# Returns:\n# Signed public URL\n# \n# Example:\n# >>> s3_obj = S3Object(s3=\"/path/to/file.txt\")\n# >>> url = client.get_presigned_s3_public_url(s3_obj)\ndef get_presigned_s3_public_url(s3_object: S3Object | str, base_url: str | None = None, expiry_secs: int | None = None) -> str\n\n# Get the current user information.\n# \n# Returns:\n# User details dictionary\ndef whoami() -> dict\n\n# Get the current user information (alias for whoami).\n# \n# Returns:\n# User details dictionary\ndef user() -> dict\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef state_path() -> str\n\n# Get the workflow state.\n# \n# Returns:\n# State value or None if not set\ndef state() -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state_pickle(value: Any, path: str = 'state.pickle') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state_pickle(path: str = 'state.pickle') -> Any\n\n# Set the state in the shared folder using pickle\ndef set_shared_state(value: Any, path: str = 'state.json') -> None\n\n# Get the state in the shared folder using pickle\ndef get_shared_state(path: str = 'state.json') -> None\n\n# Get URLs needed for resuming a flow after suspension.\n# \n# Args:\n# approver: Optional approver name\n# flow_level: If True, generate resume URLs for the parent flow instead of the\n# specific step. This allows pre-approvals that can be consumed by any later\n# suspend step in the same flow.\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_resume_urls(approver: str = None, flow_level: bool = None) -> dict\n\n# Get the resume URLs bound to one ``wait_for_approval`` step of this workflow.\n# \n# Args:\n# step_key: Checkpoint key of the approval step, as passed to\n# ``wait_for_approval(key=...)``\n# approver: Optional approver name\n# \n# Returns:\n# Dictionary with approvalPage, resume, and cancel URLs\ndef get_approval_urls(step_key: str = 'approval', approver: str = None) -> dict\n\n# Sends an interactive approval request via Slack, allowing optional customization of the message, approver, and form fields.\n# \n# **[Enterprise Edition Only]** To include form fields in the Slack approval request, use the \"Advanced -> Suspend -> Form\" functionality.\n# Learn more at: https://www.windmill.dev/docs/flows/flow_approval#form\n# \n# :param slack_resource_path: The path to the Slack resource in Windmill.\n# :type slack_resource_path: str\n# :param channel_id: The Slack channel ID where the approval request will be sent.\n# :type channel_id: str\n# :param message: Optional custom message to include in the Slack approval request.\n# :type message: str, optional\n# :param approver: Optional user ID or name of the approver for the request.\n# :type approver: str, optional\n# :param default_args_json: Optional dictionary defining or overriding the default arguments for form fields.\n# :type default_args_json: dict, optional\n# :param dynamic_enums_json: Optional dictionary overriding the enum default values of enum form fields.\n# :type dynamic_enums_json: dict, optional\n# \n# :raises Exception: If the function is not called within a flow or flow preview.\n# :raises Exception: If the required flow job or flow step environment variables are not set.\n# \n# :return: None\n# \n# **Usage Example:**\n# >>> client.request_interactive_slack_approval(\n# ... slack_resource_path=\"/u/alex/my_slack_resource\",\n# ... channel_id=\"admins-slack-channel\",\n# ... message=\"Please approve this request\",\n# ... approver=\"approver123\",\n# ... default_args_json={\"key1\": \"value1\", \"key2\": 42},\n# ... dynamic_enums_json={\"foo\": [\"choice1\", \"choice2\"], \"bar\": [\"optionA\", \"optionB\"]},\n# ... )\n# \n# **Notes:**\n# - This function must be executed within a Windmill flow or flow preview.\n# - The function checks for required environment variables (`WM_FLOW_JOB_ID`, `WM_FLOW_STEP_ID`) to ensure it is run in the appropriate context.\ndef request_interactive_slack_approval(slack_resource_path: str, channel_id: str, message: str = None, approver: str = None, default_args_json: dict = None, dynamic_enums_json: dict = None) -> None\n\n# Send a message to a Microsoft Teams conversation with conversation_id, where success is used to style the message\ndef send_teams_message(conversation_id: str, text: str, success: bool = True, card_block: dict = None)\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# Only meaningful on a data table under roles, and only for a role you are a\n# tenant of.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None)\n\n# Get a DuckLake client for DuckDB queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# \n# Returns:\n# DucklakeClient instance\ndef ducklake(name: str = 'main')\n\ndef init_global_client(f)\n\ndef deprecate(in_favor_of: str)\n\n# Get the current workspace ID.\n# \n# Returns:\n# Workspace ID string\ndef get_workspace() -> str\n\ndef get_version() -> str\n\n# Create a script job and return its job ID.\n# \n# Args:\n# hash_or_path: Script hash or path (determined by presence of '/')\n# args: Script arguments\n# scheduled_in_secs: Delay before execution in seconds\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Job ID string\ndef run_script_async(hash_or_path: str, args: Dict[str, Any] = None, scheduled_in_secs: int = None, tag: str = None) -> str\n\n# Run a script synchronously by hash and return its result.\n# \n# Args:\n# hash: Script hash\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_sync(hash: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Run a script synchronously by path and return its result.\n# \n# Args:\n# path: Script path\n# args: Script arguments\n# verbose: Enable verbose logging\n# assert_result_is_not_none: Raise exception if result is None\n# cleanup: Register cleanup handler to cancel job on exit\n# timeout: Maximum time to wait\n# tag: Override the worker tag the job runs on\n# \n# Returns:\n# Script result\ndef run_script_by_path_sync(path: str, args: Dict[str, Any] = None, verbose: bool = False, assert_result_is_not_none: bool = True, cleanup: bool = True, timeout: dt.timedelta = None, tag: str = None) -> Any\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from DuckDB\ndef duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection from Polars\ndef polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings\n\n# Convenient helpers that takes an S3 resource as input and returns the settings necessary to\n# initiate an S3 connection using boto3\ndef boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings\n\n# Get the state resource path from environment.\n# \n# Returns:\n# State path string\ndef get_state_path() -> str\n\n# Parse resource syntax from string.\ndef parse_resource_syntax(s: str) -> Optional[str]\n\n# Parse S3 object from a `s3://<storage>/<key>` URI string (`s3:///<key>`\n# for the default storage) or S3Object format. Any other string raises\n# rather than falling back to an auto-generated key: an auto key is\n# requested by omitting the object, and a fallback would silently misplace\n# the upload on any typo.\ndef parse_s3_object(s3_object: S3Object | str) -> S3Object\n\n# Parse variable syntax from string.\ndef parse_variable_syntax(s: str) -> Optional[str]\n\n# Append a text to the result stream.\n# \n# Args:\n# text: text to append to the result stream\ndef append_to_result_stream(text: str) -> None\n\n# Stream to the result stream.\n# \n# Args:\n# stream: stream to stream to the result stream\ndef stream_result(stream) -> None\n\n# Execute a SQL query against the DataTable.\n# \n# Args:\n# sql: SQL query string with $1, $2, etc. placeholders\n# *args: Positional arguments to bind to query placeholders\n# \n# Returns:\n# SqlQuery instance for fetching results\ndef query(sql: str, *args) -> SqlQuery\n\n# Idempotently materialize the rows of `select_sql` into ducklake\n# `table` for one `partition` (or the whole table when `partition` is\n# None). Client-side equivalent of the `// materialize` engine: with\n# `unique_key` it upserts within the slice (delete-by-key + insert);\n# without it, it replaces (whole table → CREATE OR REPLACE; partition →\n# delete the partition + insert). Re-running the same slice is safe — the\n# backfill / failure-recovery contract.\n# \n# The partition value is bound as a DuckDB arg (never string-interpolated)\n# so it cannot inject SQL. `select_sql` is trusted (your own query).\ndef upsert_partition(table: str, select_sql: str, partition: str = None, unique_key: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# INSERT-only materialization (no dedup / no replace) for an immutable\n# event-log table — for one `partition`, or the whole table when\n# `partition` is None. NOTE: unlike `upsert_partition`, re-running the same\n# slice duplicates rows — use only for append-only sources.\ndef append_partition(table: str, select_sql: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Read a materialized ducklake table, optionally a single partition.\ndef read(table: str, partition: str = None, partition_col: str = '_wm_partition', schema: str = None)\n\n# Execute query and fetch results.\n# \n# Args:\n# result_collection: Optional result collection mode\n# \n# Returns:\n# Query results\ndef fetch(result_collection: str | None = None)\n\n# Execute query and fetch first row of results.\n# \n# Returns:\n# First row of query results\ndef fetch_one()\n\n# Execute query and fetch first row of results. Return result as a scalar value.\n# \n# Returns:\n# First row of query result as a scalar value\ndef fetch_one_scalar()\n\n# Execute query and don't return any results.\n# \ndef execute()\n\n# DuckDB executor requires explicit argument types at declaration\n# These types exist in both DuckDB and Postgres\n# Check that the types exist if you plan to extend this function for other SQL engines.\ndef infer_sql_type(value) -> str\n\ndef parse_sql_client_name(name: str) -> tuple[str, Optional[str]]\n\n# Decorator that marks a function as a workflow task.\n# \n# Works in both WAC v1 (sync, HTTP-based dispatch) and WAC v2\n# (async, checkpoint/replay) modes:\n# \n# - **v2 (inside @workflow)**: dispatches as a checkpoint step.\n# - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API.\n# - **Standalone, or called from inside another v2 task**: executes the\n# function body directly. A task runs as a single job, so the tasks it\n# calls run in that same job, without their own options.\n# \n# A task runs as its own job, so its result is always encoded as JSON and\n# decoded back before the caller sees it: a ``datetime`` comes back as a\n# string, a tuple as a list.\n# \n# ``retry`` re-dispatches the task after a failure, inside ``@workflow`` only.\n# Every attempt is a step of its own (``call_api``, ``call_api#2``, ...) and\n# the wait between two of them is a durable sleep, so a retrying task holds no\n# worker while it backs off. Keys: ``attempts`` (retries after the first\n# failure, a whole number from 0 to 100), ``delay`` (seconds before the first\n# retry, sub-second delays dropped), ``multiplier`` (applied to the delay\n# after each attempt, 1 keeps it constant), ``max_delay`` (ceiling in\n# seconds). ``attempts`` is required, and an out-of-range or unknown key is\n# rejected where the policy is written.\n# \n# A workflow sleeps once per round, so tasks backing off in the same fan-out\n# wait one after another rather than together: the delay before a fan-out\n# retries is the sum of every backoff pending in it, not the longest one, and\n# it grows with both the width of the fan-out and ``attempts``. Retries with\n# no ``delay`` all go out in a single round.\n# \n# ``cache_ttl`` serves a previous result of the task for that many seconds\n# instead of running it again. A task is keyed on its step key (its name and\n# call order) and the workflow's input, not on the arguments it is called\n# with, so cache one only when whether it runs, and what it receives, follow\n# from the workflow's input alone. A ``task_script`` target is keyed on the\n# arguments it is called with. It has no effect on a ``task_flow`` target,\n# which keeps its flow's own cache policy.\n# \n# Usage::\n# \n# @task\n# async def extract_data(url: str): ...\n# \n# @task(path=\"f/external_script\", timeout=600, tag=\"gpu\")\n# async def run_external(x: int): ...\n# \n# @task(retry={\"attempts\": 3, \"delay\": 30, \"multiplier\": 2})\n# async def call_api(payload: dict): ...\ndef task(_func = None, *, path: Optional[str] = None, tag: Optional[str] = None, timeout: Optional[int] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill script.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# extract = task_script(\"f/data/extract\", timeout=600)\n# \n# @workflow\n# async def main():\n# data = await extract(url=\"https://...\")\ndef task_script(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Create a task that dispatches to a separate Windmill flow.\n# \n# ``retry`` takes the same policy as :func:`task`.\n# \n# Usage::\n# \n# pipeline = task_flow(\"f/etl/pipeline\", priority=10)\n# \n# @workflow\n# async def main():\n# result = await pipeline(input=data)\ndef task_flow(path: str, *, timeout: Optional[int] = None, tag: Optional[str] = None, cache_ttl: Optional[int] = None, priority: Optional[int] = None, concurrency_limit: Optional[int] = None, concurrency_key: Optional[str] = None, concurrency_time_window_s: Optional[int] = None, retry: Optional[dict] = None)\n\n# Decorator marking an async function as a workflow-as-code entry point.\n# \n# The function must be **deterministic**: given the same inputs it must call\n# tasks in the same order on every replay. Branching on task results is fine\n# (results are replayed from checkpoint), but branching on external state\n# (current time, random values, external API calls) must use ``step()`` to\n# checkpoint the value so replays see the same result.\ndef workflow(func)\n\n# Execute ``fn`` inline and checkpoint the result.\n# \n# On replay the cached value is returned without re-executing ``fn``.\n# Use for lightweight deterministic operations (timestamps, random IDs,\n# config reads) that should not incur the overhead of a child job.\n# \n# ``fn``'s result is encoded as JSON and decoded back before it is returned,\n# so the round that runs the body sees the same types every replay sees:\n# a ``datetime`` comes back as a string, a tuple as a list.\n# \n# Called from inside a task body, ``fn`` runs in place and nothing is\n# checkpointed: a task is a single job and is never replayed.\nasync def step(name: str, fn)\n\n# Server-side sleep — suspend the workflow for the given duration without holding a worker.\n# \n# Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``.\n# Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``.\nasync def sleep(seconds: int)\n\n# Suspend the workflow and wait for an external approval.\n# \n# Pass ``key`` to name the step, then ``get_approval_urls(key)`` yields the URLs\n# that resume exactly this approval — route them through your own channel.\n# Without a key the steps are named ``approval``, ``approval_2``, ...\n# \n# Returns a dict with ``value`` (form data), ``approver``, and ``approved``.\n# \n# Args:\n# timeout: Approval timeout in seconds (default 1800).\n# form: Optional form schema for the approval page.\n# self_approval: Whether the user who triggered the flow can approve it (default True).\n# key: Optional checkpoint key naming this approval step.\n# skin: ``\"minimal\"`` shows approvers only the request (form and approve/reject)\n# instead of the detailed page with the workflow's details.\n# description: Shown to approvers above the form: a string, or a rich value such as\n# ``{\"markdown\": \"...\"}``.\n# \n# Example::\n# \n# urls = await step(\"urls\", lambda: get_approval_urls(\"manager\"))\n# await step(\"notify\", lambda: send_email(urls[\"resume\"], urls[\"cancel\"]))\n# result = await wait_for_approval(key=\"manager\", timeout=3600)\nasync def wait_for_approval(timeout: int = 1800, form: dict | None = None, self_approval: bool = True, key: str | None = None, skin: Literal['detailed', 'minimal'] | None = None, description: str | dict | None = None) -> dict\n\n# Process items in parallel with optional concurrency control.\n# \n# Each item is processed by calling ``fn(item)``, which should be a @task.\n# Items are dispatched in batches of ``concurrency`` (default: all at once).\n# \n# Example::\n# \n# @task\n# async def process(item: str):\n# ...\n# \n# results = await parallel(items, process, concurrency=5)\nasync def parallel(items, fn, *, concurrency: Optional[int] = None)\n\n# Commit Kafka offsets for a trigger with auto_commit disabled.\n# \n# Args:\n# trigger_path: Path to the Kafka trigger (from event['wm_trigger']['trigger_path'])\n# topic: Kafka topic name (from event['topic'])\n# partition: Partition number (from event['partition'])\n# offset: Message offset to commit (from event['offset'])\ndef commit_kafka_offsets(trigger_path: str, topic: str, partition: int, offset: int) -> None\n\n", "agent": "# Global draft agent instructions\n\n- An agent is drafted with `write_resource`: `{ path, resource_type: \"ai_agent\", description?, value }`, where `value` is the agent's configuration described below. To change an existing agent, read it with `read_workspace_item` type \"resource\" first and write back the whole value.\n- Paths follow the conventions in the system prompt: default to `u/<current-user>/<name>` for a bare name; only use `f/<folder>/<name>` when the folder is known to exist.\n- Test the draft with `test_run_agent` before handing it over, and fix what the run shows: a test runs the draft as it stands, its tools included. Reuse one `memory_id` across calls to test follow-ups.\n- The user can review the agent on its page, the url `write_resource` returns. Deploy it with `deploy_workspace_item` (type \"resource\") once they ask, as for any other draft.\n- Before writing an inline tool, look for a deployed script that already does the job with the workspace search tools.\n\n# Windmill agent authoring reference\n\n# Windmill AI Agents\n\nAn agent, as the Agents page lists it, is a saved LLM with its own system prompt, tools and\nmemory, stored as a resource of type `ai_agent`. It is built once and used in several places: it is\nrun from its own page (a chat, or a run form), a flow's AI agent step links to it by path, and it\ncan be shared in Slack channels from its page. Build a standalone agent when the user wants an\nassistant they talk to or reuse. Build a flow when the agent is one step of a larger process.\n\n## Structure\n\n```json\n{\n \"resource_type\": \"ai_agent\",\n \"description\": \"Answers support questions from the product docs\",\n \"value\": {\n \"provider\": { \"kind\": \"openai\", \"resource\": \"$res:f/ai_providers/openai\", \"model\": \"gpt-4o\" },\n \"system_prompt\": \"You are the support assistant for Acme. Answer from the docs; say so when they don't cover a question.\",\n \"memory\": { \"kind\": \"compaction\" },\n \"output_type\": \"text\",\n \"tools\": [\n {\n \"id\": \"search_docs\",\n \"summary\": \"search_documentation\",\n \"description\": \"Search the product documentation. Use it whenever the user asks how a feature works.\",\n \"value\": {\n \"tool_type\": \"flowmodule\",\n \"type\": \"script\",\n \"path\": \"f/support/search_docs\",\n \"input_transforms\": {\n \"query\": { \"type\": \"ai\" },\n \"index\": { \"type\": \"static\", \"value\": \"product_docs\" }\n }\n }\n }\n ]\n }\n}\n```\n\nThe agent's own settings are plain values, not the `input_transforms` an agent step in a flow uses:\neach is fixed when the agent is saved. Only a tool's arguments keep `input_transforms` (see Tools). `$res:` and `$var:` references inside it are resolved at run time.\n\n- `provider` (required): `{ \"kind\", \"resource\": \"$res:<path>\", \"model\" }`, plus an optional\n `reasoning_effort`. `resource` names the workspace's AI provider resource of that kind\n- `system_prompt`: how the agent behaves. Write it for the agent's job: who it serves, what it may\n do with its tools, and what it should refuse or hand back\n- `memory`: what lets the agent see earlier turns. `{ \"kind\": \"compaction\" }` keeps the whole\n conversation, summarizing its older part as it nears the model's context window; it is what a new\n agent starts with on its page. `{ \"kind\": \"off\" }` makes every run start from nothing, right for an\n agent that handles one request per run\n- `output_type`: `text` (default) or `image`. Image output ignores tools and needs S3 storage on the\n workspace\n- `output_schema`: a JSON schema the answer must follow, for an agent whose output a program reads\n- `max_iterations`: how many model and tool rounds a run may take, 1 to 1000 (default 10)\n- `streaming` (default on), `temperature`, `max_completion_tokens`: as their names say\n- `run_on_behalf_of`: runs from the agent's page take the identity the agent was deployed with\n rather than the caller's, so people can use it without access to what its tools touch.\n `slack_anyone` lets anyone in the Slack channels it is shared in ask it, and is kept only with\n `run_on_behalf_of`. Set either only when the user asks: both widen who acts with the deployer's\n rights\n- `on_behalf_of` is the identity itself. Deploying sets it, so never write it\n\n## Tools\n\n`tools` takes the same entries as a flow's AI agent step. `value.tool_type` is `flowmodule` for a\nscript or inline script the agent calls (or a nested agent or AI decision), `mcp` for an MCP server\n(`{ \"tool_type\": \"mcp\", \"resource_path\": \"$res:<path>\", \"include_tools\": [], \"exclude_tools\": [] }`),\nor `websearch` for web search (`{ \"tool_type\": \"websearch\" }`, summary `Web Search`).\n\n- Write logic made for this agent as an inline `rawscript` tool, as a flow writes its steps. Point a\n `script` tool at a deployed script (`path`) only when one already does the job: a run calls the\n deployed version, so a script that exists only as a draft fails the run. An inline tool's\n `value` is a flow's rawscript step:\n `{ \"tool_type\": \"flowmodule\", \"type\": \"rawscript\", \"language\": \"bun\", \"content\": \"export async function main(query: string) { ... }\", \"input_transforms\": { \"query\": { \"type\": \"ai\" } } }`\n- A flow cannot be a tool: a run offered one fails with `Unsupported tool`. Wrap it in a script\n that runs the flow\n- A flowmodule tool's `summary` is the name the agent calls it by: letters, numbers and underscores\n only, unique among the agent's tools, and neither a reserved step id (a JavaScript keyword, `ctx`,\n `state`, `bg`) nor `__wm_web_search`. Put the explanation in `description`, which tells the agent\n when to call it\n- Each argument of a tool is either the model's or fixed. `{ \"type\": \"ai\" }` (or no value) lets the\n model fill it; a static value fixes it and hides it from the model. Fix what the model must not\n choose, such as a resource, a table name or a limit\n\n## Using It From a Flow\n\nAn AI agent step links to a saved agent with `value.agent` instead of carrying its own `provider`,\nsystem prompt and tools:\n\n```json\n{\n \"id\": \"support\",\n \"value\": {\n \"type\": \"aiagent\",\n \"agent\": \"f/support/support_agent\",\n \"input_transforms\": {\n \"user_message\": { \"type\": \"javascript\", \"expr\": \"flow_input.question\" }\n },\n \"tools\": []\n }\n}\n```\n\nThe step holds only what belongs to one use of the agent: `user_message`, `user_attachments`,\n`enabled_tools`, `memory_id`, `previous_messages`, and the `model` and `reasoning_effort` overrides.\nIts `value.tool_inputs` (`{ \"<tool id>\": { \"<argument>\": <input transform> } }`) wires a saved\ntool's arguments to this flow, e.g. `flow_input.customer_id`, over the transforms the agent saved,\nwithout changing the agent. Everything else comes from the agent, so a change to the agent reaches\nevery flow linking it.\n", "datatable": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role <name>`, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('<name>')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## TypeScript Datatable API (windmill-client)\n\nImport: `import * as wmill from 'windmill-client'`\n\nSQL statement object with query content, arguments, and execution methods\n```typescript\ntype SqlStatement<T> = {\n /** Raw SQL content with formatted arguments */\n content: string;\n\n /** Argument values keyed by parameter name */\n args: Record<string, any>;\n\n /**\n * Execute the SQL query and return results\n * @param params - Optional parameters including result collection mode\n * @returns Query results based on the result collection mode\n */\n fetch<ResultCollectionT extends ResultCollection = \"last_statement_all_rows\">(\n params?: FetchParams<ResultCollectionT | ResultCollection> // The union is for auto-completion\n ): Promise<SqlResult<T, ResultCollectionT>>;\n\n /**\n * Execute the SQL query and return only the first row\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOne(\n params?: Omit<FetchParams<\"last_statement_first_row\">, \"resultCollection\">\n ): Promise<SqlResult<T, \"last_statement_first_row\">>;\n\n /**\n * Execute the SQL query and return only the first row as a scalar value\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOneScalar(\n params?: Omit<\n FetchParams<\"last_statement_first_row_scalar\">,\n \"resultCollection\"\n >\n ): Promise<SqlResult<T, \"last_statement_first_row_scalar\">>;\n\n /**\n * Execute the SQL query without fetching rows\n * @param params - Optional parameters\n */\n execute(\n params?: Omit<FetchParams<\"last_statement_first_row\">, \"resultCollection\">\n ): Promise<void>;\n};\n```\n\n```typescript\n// Template tag function: sql`SELECT * FROM table WHERE id = ${id}`.fetch()\ninterface DatatableSqlTemplateFunction {\n // Tagged template usage:\n <T = any>(strings: TemplateStringsArray, ...values: any[]): SqlStatement<T>;\n query<T = any>(sql: string, ...params: any[]): SqlStatement<T>;\n};\n```\n\nCreate a SQL template function for PostgreSQL/datatable queries\n@param name - Database/datatable name (default: \"main\")\n@param opts.role - Connect as this data table role instead of the data table's default one.\n Only meaningful on a data table under roles, and only for a role you are a tenant of.\n@returns SQL template function for building parameterized queries\n@example\nlet sql = wmill.datatable()\nlet name = 'Robin'\nlet age = 21\nawait sql`\n SELECT * FROM friends\n WHERE name = ${name} AND age = ${age}::int\n`.fetch()\n@example\n// Read through a restricted role\nlet sql = wmill.datatable(\"main\", { role: \"analytics\" })\n```typescript\nfunction datatable(name: string = \"main\",\n opts?: DatatableOptions): DatatableSqlTemplateFunction\n```\n", "datatable.python3": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role <name>`, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('<name>')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", "datatable.go": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role <name>`, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('<name>')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## TypeScript Datatable API (windmill-client)\n\nImport: `import * as wmill from 'windmill-client'`\n\nSQL statement object with query content, arguments, and execution methods\n```typescript\ntype SqlStatement<T> = {\n /** Raw SQL content with formatted arguments */\n content: string;\n\n /** Argument values keyed by parameter name */\n args: Record<string, any>;\n\n /**\n * Execute the SQL query and return results\n * @param params - Optional parameters including result collection mode\n * @returns Query results based on the result collection mode\n */\n fetch<ResultCollectionT extends ResultCollection = \"last_statement_all_rows\">(\n params?: FetchParams<ResultCollectionT | ResultCollection> // The union is for auto-completion\n ): Promise<SqlResult<T, ResultCollectionT>>;\n\n /**\n * Execute the SQL query and return only the first row\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOne(\n params?: Omit<FetchParams<\"last_statement_first_row\">, \"resultCollection\">\n ): Promise<SqlResult<T, \"last_statement_first_row\">>;\n\n /**\n * Execute the SQL query and return only the first row as a scalar value\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOneScalar(\n params?: Omit<\n FetchParams<\"last_statement_first_row_scalar\">,\n \"resultCollection\"\n >\n ): Promise<SqlResult<T, \"last_statement_first_row_scalar\">>;\n\n /**\n * Execute the SQL query without fetching rows\n * @param params - Optional parameters\n */\n execute(\n params?: Omit<FetchParams<\"last_statement_first_row\">, \"resultCollection\">\n ): Promise<void>;\n};\n```\n\n```typescript\n// Template tag function: sql`SELECT * FROM table WHERE id = ${id}`.fetch()\ninterface DatatableSqlTemplateFunction {\n // Tagged template usage:\n <T = any>(strings: TemplateStringsArray, ...values: any[]): SqlStatement<T>;\n query<T = any>(sql: string, ...params: any[]): SqlStatement<T>;\n};\n```\n\nCreate a SQL template function for PostgreSQL/datatable queries\n@param name - Database/datatable name (default: \"main\")\n@param opts.role - Connect as this data table role instead of the data table's default one.\n Only meaningful on a data table under roles, and only for a role you are a tenant of.\n@returns SQL template function for building parameterized queries\n@example\nlet sql = wmill.datatable()\nlet name = 'Robin'\nlet age = 21\nawait sql`\n SELECT * FROM friends\n WHERE name = ${name} AND age = ${age}::int\n`.fetch()\n@example\n// Read through a restricted role\nlet sql = wmill.datatable(\"main\", { role: \"analytics\" })\n```typescript\nfunction datatable(name: string = \"main\",\n opts?: DatatableOptions): DatatableSqlTemplateFunction\n```\n\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", "pipeline": "# Data pipeline authoring\n\nA **data pipeline** is NOT a flow. A flow is one runnable that orchestrates steps internally. A data pipeline is a set of **independent scripts**, each deployed on its own, that form a DAG by reading and writing shared **storage assets** (DuckLake tables, data tables, S3 objects, volumes, resources) and by declaring execution **triggers**. The pipeline is visualized and edited at `/pipeline/<folder>`; every node is a normal workspace script that happens to carry pipeline annotations. When the user asks for a \"data pipeline\" (or to \"ingest / transform / materialize\" data across steps), build pipeline-annotated scripts — do NOT build a flow.\n\n## Default to DuckDB + DuckLake\n\nA pipeline node that produces a table should almost always be a **`duckdb`** node that materializes its output into a **DuckLake** table with `-- materialize ducklake://<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:\n\n- `postgresql` / data tables — only for row-level, OLTP-style mutations against an existing Postgres data table (frequent single-row upserts/updates, transactional reads that an app queries live).\n- `bun` / `python3` — only for work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node produces tabular data for downstream steps, write it **straight into DuckLake** (or a data table) from the same script — see \"Ingesting from Python / TypeScript\" below — rather than inventing a parallel store.\n\nDo not spread a pipeline across postgres, S3, and DuckLake when one DuckLake lake would do; a consistent DuckLake lakehouse is the goal.\n\n## Ingesting from Python / TypeScript\n\nA node that fetches data in code (an API, a SaaS export, a scraper) writes the rows **directly** into their DuckLake table with `wmill.ducklake()`, or into a data table with `wmill.datatable()`. DuckLake already stores every table as parquet files in the workspace object storage, so **never stage the raw payload first** — no intermediate JSON / CSV / parquet file in S3 and no second \"load the raw file\" node. One ingestion node, one table.\n\nPass the rows as a query argument (a list of dicts / array of objects is sent as JSON) and let SQL unnest them; declare the column types so the table gets a real schema:\n\n```python\n# pipeline\n# on schedule\nimport wmill\n\ndef main():\n rows = fetch_charges() # list[dict]\n lake = wmill.ducklake()\n lake.query(\"\"\"\n CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json($rows, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)\n \"\"\", rows=rows).fetch()\n```\n\n```ts\n// pipeline\n// on schedule\nimport * as wmill from \"windmill-client\"\n\nexport async function main() {\n const rows = await fetchCharges()\n const lake = wmill.ducklake()\n await lake`CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json(${rows}, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)`.fetch()\n}\n```\n\n- Use `INSERT INTO <table> SELECT ...` instead of `CREATE OR REPLACE` to append (an incremental pull), with a one-time `CREATE TABLE IF NOT EXISTS` first.\n- Assign the client to a variable (`lake = wmill.ducklake()`) and keep the SQL a **string literal** (Python) or a template without `sql.raw` (TS): that is what lets the graph record the node's write to `ducklake://main/<table>`. A chained `wmill.ducklake().query(...)` or SQL built in a variable records no output, so the downstream edge never forms.\n- `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).\n- The downstream node triggers on the table itself: `-- on ducklake://main/stripe_charges`.\n\n## Storage prerequisites\n\nA DuckLake pipeline only runs once the workspace has **object storage** (S3 / Azure Blob / GCS) **and a DuckLake catalog** configured — DuckLake tables and `s3://` assets can't be materialized or read without it. Check which DuckLake catalogs the workspace has before you build.\nDrafting the annotated scripts does not require storage, but the pipeline can't ingest, materialize, or read its assets until it exists. So if there is none (or the user hits \"storage not configured\" errors), say so and give the right next step **by role**:\n\n- a workspace **admin** sets it up in Workspace settings → Object Storage (add an S3/Azure/GCS storage), then adds a DuckLake catalog on top of it;\n- anyone **without admin rights** should ask a workspace admin to configure object storage + a DuckLake catalog.\n\nNever hand back a DuckLake pipeline that cannot run without flagging the missing storage and pointing to who sets it up.\n\n## What makes a script a pipeline node\n\nA script joins the pipeline when its source begins with the `pipeline` annotation as a top-of-file comment, **written in the script's own comment syntax** — `//` for TS/JS (bun), `--` for SQL (DuckDB/Postgres), `#` for Python/Bash. So it's `-- pipeline` in a DuckDB node, `# pipeline` in a Python node, `// pipeline` in a bun node. Every annotation below uses that same prefix (the `//` shown is the TS form). All other wiring is expressed as annotation comments near the top of the file:\n\n- `// on <ref>` — declares an execution-DAG **input** (what triggers/feeds this node). `<ref>` is either:\n - an **asset URI** (the node runs when that asset is produced upstream): `ducklake://main/orders`, `datatable://main/users`, `$res:f/folder/my_resource`, `volume://name/path`, or an S3 object (see the S3 storage-form rule below).\n - a **native trigger kind**: `schedule`, `webhook`, `email`, `kafka`, `mqtt`, `amqp`, `nats`, `postgres`, `sqs`, `gcp`, or `data_upload` (a user-uploaded S3 file). For these the actual trigger row (cron, topic, …) is created separately; the annotation only declares the binding. **`data_upload` is special**: there is no trigger row — the node instead declares an **`S3Object` input parameter** fed by the auto-generated upload picker; it never hard-codes a key. Any language can be the `data_upload` node:\n - Python (has `import wmill`): `def main(file: wmill.S3Object):` then `wmill.load_s3_file(file)`; TS (has `import * as wmill from \"windmill-client\"`): `export async function main(file: wmill.S3Object)`. Qualify the type as `wmill.S3Object` (or add `from wmill import S3Object` / `import { S3Object } from \"windmill-client\"`) — a bare `S3Object` is undefined.\n - **DuckDB** takes the s3object arg via a `-- $<name> (s3object)` declaration and reads it directly, so a single DuckDB node can ingest **and** materialize:\n ```\n -- pipeline\n -- on data_upload\n -- materialize ducklake://main/raw_uploads\n -- $file (s3object)\n SELECT * FROM read_csv($file)\n ```\n- **Outputs** are inferred from what the body writes — a `CREATE TABLE`, a `wmill.writeS3File(...)`, a DuckLake/datatable write. To declare a managed output explicitly, use `// materialize <asset-uri>`.\n- Optional badges: `// partitioned <daily|hourly|weekly|monthly|dynamic>`, `// freshness <duration>` (e.g. `1h`), `// tag <worker-tag>`, `// retry <count> [delay]`, `// data_test <kind> ...` (managed DuckLake targets only — deploy rejects it beside a `dbt://` one), `// measure <name> = <agg> [where <pred>]` and `// dimension <name> = <expr>` (see \"Declared metrics\" below).\n\n## S3 object wiring (storage form matters)\n\nAn `s3://` URI's first slashes select the **storage**, not part of the key — get this wrong and the producer/consumer edge silently won't connect:\n\n- `s3:///<key>` (**triple** slash, empty first segment) = the **default** workspace storage. A downstream node reading or triggering on that object uses `s3:///<key>` — e.g. DuckDB `-- on s3:///orders/2024.parquet` and `read_parquet('s3:///orders/2024.parquet')`.\n- `s3://<storage>/<key>` (**double** slash, non-empty first segment) = a **named secondary** storage called `<storage>` — so `s3://ingest/x` means storage `ingest`, key `x`, NOT key `ingest/x`. Only use this when the object genuinely lives in a configured secondary storage; never invent a bucket/storage name for a default-storage object (it breaks the edge).\n\nTo make the producer side visible to lineage, a Python/TS node MUST pass the **`S3Object` form**, not a bare key string: Python `wmill.write_s3_file(wmill.S3Object(s3=\"<key>\"), data)` (or the import-free dict `{\"s3\": \"<key>\"}`), TS `wmill.writeS3File({ s3: \"<key>\" }, data)`. That records the default-storage asset `/<key>`, which a downstream `s3:///<key>` reader connects to (same key both sides). A bare `write_s3_file(\"<key>\", ...)` records **no** asset and produces **no** edge. Add `storage=\"<name>\"` only for a named secondary storage.\n\nThe key must be a **string literal** — the graph parser is static and cannot follow a variable, f-string, or computed path, so `write_s3_file(wmill.S3Object(s3=key_var), ...)` records no edge. Inline the literal (`s3=\"events/user_events.parquet\"`) on both the writing and reading node. The same rule applies to every asset URI in an annotation or SDK call (`ducklake://`, `datatable://`, `s3://`): write them literally, not via a variable.\n\n## Materialize (the managed output)\n\n> **A MANAGED `// materialize` is DuckDB-only**, and its target must be a DuckLake table (`ducklake://<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.\n>\n> The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: `// materialize manual dbt://<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.\n\nA managed `// materialize ducklake://<name>/<table>` tells the runtime to write the node's output table **for you**: write the body as a single `SELECT` and the runtime wraps it in the create/replace — do **not** also write your own `CREATE TABLE` / `INSERT`. (The opposite holds for the `dbt://` target above: there the node writes its own DDL and the strategies below do not apply.)\n\nA target that names no table — `// materialize`, `// materialize ducklake://<name>`, or options alone such as `// materialize key=id` — writes the table named after the script: node `f/shop/orders_daily` materializes `ducklake://main/orders_daily` (characters other than letters, digits and `_` become `_`, and a name starting with a digit gets a leading `_`). Name the node after the table it produces and the bare form is enough; write the full target when the table's name differs from the node's, and use that same name in every downstream `// on` and read.\n\nWrite strategy:\n\n- no option → **replace** the whole table each run (full refresh; the only mode whose output columns may change);\n- `// materialize <uri> append` → INSERT-append rows (incremental);\n- `// materialize <uri> key=<col>` → merge/upsert on `<col>`.\n\n`// materialize manual <uri>` opts **out** of managed writes — the script writes its own DDL and the annotation only records the output asset for lineage.\n\n`materialize` pairs with partitioning for incremental pipelines: a `// partitioned <daily|hourly|weekly|monthly|dynamic>` node runs **once per partition** (append/merge into a fixed-schema table). The `{partition}` token, usable in any asset URI **and** in the body SQL, is replaced at run time by the current partition's **identity string**:\n\n- To filter the source to the active slice on a time grain, use the runtime-injected macro: `WHERE wm_partition(<ts_col>) = {partition}`. `wm_partition(ts)` buckets a timestamp in exactly the identity format the runtime uses for daily/hourly/weekly/monthly, so it always matches; never hand-write a `strftime` format.\n- Do NOT write `= TIMESTAMP {partition}`: the identity string is not a valid timestamp literal for hourly/weekly/monthly and errors at run time.\n- For `dynamic` partitioning the identity is the caller-supplied key (not a timestamp, no macro), so filter on it directly: `WHERE <your_key_col> = {partition}`.\n\n`materialize` is an output **declaration** on a node — not a command. There is no \"materialize run\".\n\n## Declared metrics (`measure` / `dimension`)\n\nOn a node that materializes a DuckLake table, `// measure <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 reuse the definition instead of re-deriving it and silently disagreeing.\n\n- Keep the predicate in the `where` clause rather than folding it into the aggregate: it is rendered as `<agg> FILTER (WHERE <pred>)`, which is what lets two measures with different predicates share one GROUP BY.\n- DuckLake-only, and only meaningful next to `// materialize`.\n- Declare one when a number carries a judgement call someone else would get wrong (refunds excluded, test rows dropped, which column is the amount); do NOT blanket every table with measures — an obvious `count(*)` earns nothing.\n- To use a metric another node declares, read that node and reuse its exact expression rather than guessing it.\n\n## How to build one\n\n1. Put every node in the **same folder**: `f/<folder>/<name>`. The folder is the pipeline.\n2. Write each node as its own script. Default to `duckdb` materializing into DuckLake (see \"Default to DuckDB + DuckLake\" above); pick `postgresql`, `bun`, or `python3` only when that section says the work calls for it.\n3. Start each body with `// pipeline`, then the `// on` input declarations, then the transform that writes the output.\n4. **Chain nodes by asset URI**: read an upstream node's output asset, then `// on <that-same-uri>` in the downstream node so the edge forms. Reuse exact asset paths from existing nodes rather than inventing parallel ones.\n5. Never guess the columns of a file or table you have not seen: read them first with a query that writes nothing, such as `DESCRIBE SELECT * FROM read_csv('s3:///raw/orders/*.csv')` or `ATTACH 'ducklake://main' AS lake; DESCRIBE lake.orders`, and use those exact column names. A test run of a node that materializes a table writes that table into the workspace's lake: test-run such a node only while its table does not exist yet, and ask before running one that would replace a table already there.\n6. Don't deploy nodes unless the user asks to. A pipeline only \"runs\" once its scripts are deployed and their triggers exist.\n\n## Example (DuckDB → DuckLake, scheduled ingest + downstream transform)\n\nNode `f/sales/orders_ingest` (runs on a schedule, materializes a DuckLake table):\n\n```sql\n-- pipeline\n-- on schedule\n-- materialize ducklake://main/orders\nSELECT * FROM read_csv('s3:///raw/orders/*.csv')\n```\n\nNode `f/sales/orders_daily` (runs when `orders` is produced, writes a rollup):\n\n```sql\n-- pipeline\n-- on ducklake://main/orders\n-- materialize ducklake://main/orders_daily\nATTACH 'ducklake://main' AS lake;\nSELECT date_trunc('day', ts) AS day, count(*) AS n\nFROM lake.orders GROUP BY 1\n```\n\nA node reads a DuckLake table only through a lake it attaches itself (`ATTACH 'ducklake://<name>' AS lake;`, then `lake.<table>`); the materialize target is attached by the runtime under a name of its own, so `ducklake.main.<table>` does not resolve.\n", - "workspace_settings": "# Workspace settings\n\nEverything an admin sets on the Workspace settings page is one document: a mapping of top-level\nkeys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can\nread or change it.\n\n## Applying a document\n\n- A partial document changes only the keys it states; every key it omits is left as it is.\n- Each key is replaced whole, so read its current value and send it back edited: a nested object\n given with one field replaces the stored object with that one field.\n- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`.\n- Each setting is written through the same path the settings page uses, with the same validation\n and audit log. The writes are not one transaction: when one fails the apply stops, and the\n error says what was already written.\n- A dry run reports the changes, as `before` / `after` per key, without writing anything.\n- `name` is never applied: rename a workspace on the settings page. `color` is applied only when\n set to a value, so `null` does not clear it.\n- A key the server does not know is ignored and named in the warnings: check them, since a typo\n otherwise reads as \"nothing to change\".\n- A setting this edition does not offer (Enterprise only) is refused, by the dry run too.\n\n## Secrets\n\n`slack_oauth_client_secret` is the one secret. A read shows `__SENSITIVE_AND_UNCHANGED__` in place\nof a set secret; sending that placeholder back keeps the stored value. A value starting with\n`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key\nis left unchanged with a warning; any other value is taken as plaintext. Never\nwrite a secret you were not given: keep the placeholder.\n\n## Keys\n\n| Key | Value |\n|---|---|\n| `auto_invite` | `{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. |\n| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path? }`, `path` being `script/<path>` or `flow/<path>`. |\n| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. |\n| `webhook` | URL POSTed a JSON event on every change to the workspace's items. |\n| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. |\n| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. |\n| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. |\n| `datatable` | `{ datatables: { <name>: { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. |\n| `datatable_permissions` | `{ <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. |\n| `protection_rules` | `{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }`, 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. |\n| `ducklake` | `{ ducklakes: { <name>: { catalog, storage, ... } } }`. |\n| `dbt_warehouses` | dbt warehouse connections. |\n| `default_app` | Path of the app shown as the workspace home. |\n| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |\n| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |\n| `role_overrides` | `{ <role>: { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. |\n| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |\n| `mute_critical_alerts` | Mute the workspace's critical alerts. |\n| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |\n| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. |\n| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. |\n| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. |\n| `guest_jwt_public_key`, `guest_jwt_jwks_url` | The key that signs guest JWTs for apps set to Guests. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n" + "workspace_settings": "# Workspace settings\n\nEverything an admin sets on the Workspace settings page is one document: a mapping of top-level\nkeys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can\nread or change it.\n\n## Applying a document\n\n- A partial document changes only the keys it states; every key it omits is left as it is.\n- Each key is replaced whole, so read its current value and send it back edited: a nested object\n given with one field replaces the stored object with that one field.\n- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`.\n- Each setting is written through the same path the settings page uses, with the same validation\n and audit log. The writes are not one transaction: when one fails the apply stops, and the\n error says what was already written.\n- A dry run reports the changes, as `before` / `after` per key, without writing anything.\n- `name` is never applied: rename a workspace on the settings page. `color` is applied only when\n set to a value, so `null` does not clear it.\n- A key the server does not know is ignored and named in the warnings: check them, since a typo\n otherwise reads as \"nothing to change\".\n- A setting this edition does not offer (Enterprise only) is refused, by the dry run too.\n\n## Secrets\n\n`webhook` (its URL usually carries the receiver's token) and `slack_oauth_client_secret` are the\nsecrets. A read shows `__SENSITIVE_AND_UNCHANGED__` in place\nof a set secret; sending that placeholder back keeps the stored value. A value starting with\n`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key\nis left unchanged with a warning; any other value is taken as plaintext. Never\nwrite a secret you were not given: keep the placeholder.\n\n## Keys\n\n| Key | Value |\n|---|---|\n| `auto_invite` | `{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. |\n| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path? }`, `path` being `script/<path>` or `flow/<path>`. |\n| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. |\n| `webhook` | URL POSTed a JSON event on every change to the workspace's items. |\n| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. |\n| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. |\n| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. |\n| `datatable` | `{ datatables: { <name>: { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. |\n| `datatable_permissions` | `{ <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. |\n| `protection_rules` | `{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }`, 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. |\n| `ducklake` | `{ ducklakes: { <name>: { catalog, storage, ... } } }`. |\n| `dbt_warehouses` | dbt warehouse connections. |\n| `default_app` | Path of the app shown as the workspace home. |\n| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |\n| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |\n| `role_overrides` | `{ <role>: { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. |\n| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |\n| `mute_critical_alerts` | Mute the workspace's critical alerts. |\n| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |\n| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. |\n| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. |\n| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. |\n| `guest_jwt_public_key`, `guest_jwt_jwks_url` | The key that signs guest JWTs for apps set to Guests. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n", + "display": "# Rich results\n\nWindmill renders a script's or flow's return value according to its shape: on run pages, in the\nscript and flow editors, in app result displays and in AI chat run cards. Anything that matches none\nof the shapes below is shown as JSON.\n\n## Shapes\n\n- `{ \"table-row-object\": [{...}, ...] }`, or a bare array of objects: a table whose columns are the\n union of the objects' keys.\n- `{ \"table-col\": { \"col\": [...], ... } }`, or a bare object of equal-length arrays: a table built\n column by column.\n- `{ \"table-row\": [[\"col\", ...], [v, ...], ...] }`: a table whose first row holds the column names.\n- `{ \"chart\": {...} }`: a bar, line, pie or scatter chart drawn from rows (schema below). A `chart`\n value the schema rejects is shown as JSON, not as a broken chart.\n- `{ \"markdown\": \"...\" }` (or `md`): rendered markdown.\n- `{ \"html\": \"...\" }`: sanitized HTML.\n- `{ \"png\": \"<base64>\" }`, likewise `jpeg`, `gif`, `svg`: an image. `{ \"pdf\": \"<base64>\" }`: a PDF.\n- `{ \"file\": \"<base64>\", \"filename\": \"report.csv\" }`: a download.\n- `{ \"map\": { \"lat\": 0, \"lon\": 0, \"zoom\": 3, \"markers\": [{ \"lat\": 0, \"lon\": 0, \"title\": \"...\" }] } }`:\n a map.\n- `{ \"s3\": \"path/to/key\" }`: an object in the workspace storage, previewed by type.\n- `{ \"render_all\": [ ... ] }`: each item rendered in turn with the rules above.\n\nEach shape is an object with that one key (plus `filename` for a file, and an optional `storage` for\n`s3`). A result carrying any other key beside it is shown as JSON.\n\n## Choosing one\n\nA chart answers a question at a glance: a trend over time (line), a comparison across categories\n(bar), parts of a whole with few parts (pie), or a relation between two numbers (scatter). A table\nanswers lookups and holds the exact values. When both help, return both in a `render_all`: the chart\nfirst, then the table of the same rows.\n\nKeep a chart to what it shows well: at most 8 series. A pie with more than 8 slices keeps the 7\nlargest and folds the rest into \"Other\", so prefer a bar chart for many categories. Aggregate before\ncharting: a chart of thousands of raw points says less than one of the totals per day.\n\n\n### Chart and table schema\n\nA chart or table value, as JSON Schema. Beyond it: `x` and every `y` must be columns of `data`, `y` columns hold numbers, a scatter chart's `x` column holds numbers, and a pie chart takes exactly one `y`.\n\n```json\n{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\",\"anyOf\":[{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]},{\"type\":\"object\",\"properties\":{\"render_all\":{\"description\":\"Several items shown one after another\",\"minItems\":1,\"maxItems\":10,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]}}},\"required\":[\"render_all\"],\"additionalProperties\":false}]}\n```\n\nBar chart, one series per y column:\n\n```json\n{\n \"chart\": {\n \"type\": \"bar\",\n \"title\": \"Runs per day\",\n \"data\": [\n {\n \"day\": \"2026-11-10\",\n \"success\": 42,\n \"failure\": 3\n },\n {\n \"day\": \"2026-11-11\",\n \"success\": 51,\n \"failure\": 1\n }\n ],\n \"x\": \"day\",\n \"y\": [\n \"success\",\n \"failure\"\n ],\n \"stacked\": true\n }\n}\n```\n\nPie chart (exactly one y column):\n\n```json\n{\n \"chart\": {\n \"type\": \"pie\",\n \"data\": [\n {\n \"language\": \"python3\",\n \"scripts\": 18\n },\n {\n \"language\": \"bun\",\n \"scripts\": 25\n }\n ],\n \"x\": \"language\",\n \"y\": \"scripts\"\n }\n}\n```\n\nA chart and a table together:\n\n```json\n{\n \"render_all\": [\n {\n \"chart\": {\n \"type\": \"line\",\n \"data\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180\n }\n ],\n \"x\": \"hour\",\n \"y\": \"p95_ms\",\n \"y_label\": \"ms\"\n }\n },\n {\n \"table-row-object\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120,\n \"jobs\": 310\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180,\n \"jobs\": 402\n }\n ]\n }\n ]\n}\n```\n", + "code_mode": "# Solving a task with code\n\nWhen the user asks for something done against the systems their workspace connects to (look\nsomething up in an API, move data, check a status), answer it with a Windmill script run as a\npreview: it executes on the workspace's workers, with its resources. A script that worked can be\nsaved and run as is the next time.\n\n1. **Look for a saved script first**, by the user's words and by the system the task touches. If\n one fits, run it rather than writing new code; if one nearly fits, offer to change it rather\n than writing a near-duplicate.\n2. **Otherwise write one script and run it as a preview.** Do the fetching, filtering and\n combining in the code, and return only what answers the task, not raw API payloads. Take\n credentials as a resource-typed `main` parameter, passed as `$res:<path>` when running, never\n as a token in the code. Give `main` typed parameters for whatever would change between runs,\n so the script is reusable.\n3. **Offer to save it** when the task is likely to come back, without saving it unasked. Saving\n makes a draft, deployed only when the user asks; from then on it is an ordinary script.\n\nFor a third-party API, look up its hub integration for its resource type and how to call it.\n\n" } } diff --git a/backend/windmill-api/src/ai_session_tools/gen/prompt.json b/backend/windmill-api/src/ai_session_tools/gen/prompt.json index c88c8dd9e6..0e4433314c 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/prompt.json +++ b/backend/windmill-api/src/ai_session_tools/gen/prompt.json @@ -1,5 +1,5 @@ { - "template": "This server works in a Windmill workspace as the user \"{{username}}\".{{#read_only}}{{#runs_deployed}}\n\nThis connection can read the workspace's items, runs and data, and run scripts, flows and agents that are already deployed. It cannot create, edit, deploy or delete anything, nor test-run code that is not deployed: when the user asks for such a change, say plainly that this connection cannot make it, rather than describing steps as if you had made it.{{/runs_deployed}}{{^runs_deployed}}\n\nThis connection is read-only: it can read the workspace's items, runs and data, but cannot run, create, edit, deploy or delete anything. When the user asks for a run or a change, say plainly that this connection cannot make it, rather than describing steps as if you had made it.{{/runs_deployed}}{{/read_only}}{{^read_only}}{{^can_write_draft}}\n\nThis user's role does not let them create or edit {{refused_kinds}} here, so when they ask for such a change, say plainly that you cannot make it rather than describing steps as if you had, and suggest asking a workspace admin, who can grant their role more.{{#builds_flows}} Their role does let them compose flows out of scripts and flows that are already deployed: write flows with write_flow and patch_flow_json, every step calling a deployed script or flow by path. The server refuses inline code anywhere in the flow, so when a flow needs logic no deployed script provides, say so and suggest asking a workspace admin for that script.{{/builds_flows}}{{#builds_apps}} Their role does let them build raw apps whose backend runnables are path runnables to deployed scripts or flows; call get_instructions with subject \"app\" first. The server refuses inline and hub runnables, and runs an app they deploy sandboxed, as the user who deployed it.{{/builds_apps}}{{#has_draft_tools}} They can draft with {{draft_tools}}.{{/has_draft_tools}}{{/can_write_draft}}{{/read_only}}\n\nRules:{{#can_write_any_draft}}\n- What you write is a per-user draft, saved server-side and visible only to this user. {{#can_deploy}}Nothing reaches the workspace until deploy_workspace_item deploys it, which you call only when the user asks.{{/can_deploy}}{{^can_deploy}}{{#can_deploy_any_kind}}Nothing reaches the workspace until it is deployed, and this workspace's deploy rules let this user deploy only the schedules and triggers their role manages: call deploy_workspace_item for those only when the user asks, and for anything else give them the draft's link and say it needs deploying by someone allowed to.{{/can_deploy_any_kind}}{{^can_deploy_any_kind}}Nothing reaches the workspace until it is deployed, which this workspace's deploy rules do not let this user do: when a draft is ready, give them its link and say it needs deploying by someone allowed to.{{/can_deploy_any_kind}}{{/can_deploy}}{{/can_write_any_draft}}\n{{#can_write_any_draft}}- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, a draft's editor (`url`), an app draft's editor with its live preview (`preview_url`), a deployed item's page. Whenever the user will want to see what you built or ran, or has to do a step in Windmill themselves: show it with show_run, show_runs, show_item or show_deploy_review when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link.{{/can_write_any_draft}}{{^can_write_any_draft}}- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, an item's page. Whenever the user will want to see what you found{{#runs}} or ran{{/runs}}, or has to do a step in Windmill themselves: show it with show_run, show_runs or show_item when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link.{{/can_write_any_draft}}\n- Find items with list_workspace_items and read one with read_workspace_item{{#can_write_any_draft}} before changing it{{/can_write_any_draft}}. An agent is a resource of type `ai_agent`{{#runs}}: {{#can_run_flow_preview}}test it with test_run_agent and {{/can_run_flow_preview}}run a deployed one with run_agent, never run_flow or run_script.{{/runs}}{{^runs}}.{{/runs}}{{#can_write_draft}}\n- Call get_instructions before writing a script, flow, agent, resource or app, a data pipeline or a datatable migration. For a script, pass its language.{{#can_draft_triggers}} Call get_trigger_schema before write_trigger, since each trigger kind takes different fields, and{{/can_draft_triggers}}{{^can_draft_triggers}} Call{{/can_draft_triggers}} get_db_schema before writing SQL against a database resource.{{/can_write_draft}}{{^can_write_draft}}{{#can_draft_resources}}\n- Call get_instructions before writing a resource.{{#can_draft_triggers}} Call get_trigger_schema before write_trigger, since each trigger kind takes different fields.{{/can_draft_triggers}}{{/can_draft_resources}}{{/can_write_draft}}{{#can_write_draft}}{{#can_run_preview}}\n- After writing a script, flow, agent or app runnable, test it with test_run_script, test_run_flow, test_run_step, test_run_agent or test_run_app_runnable before saying it works. They run the draft, so nothing needs deploying.{{/can_run_preview}}{{/can_write_draft}}{{^can_write_draft}}{{#builds_flows}}{{#can_run_flow_preview}}\n- After writing a flow, test it with test_run_flow before saying it works. It runs the draft, so nothing needs deploying.{{/can_run_flow_preview}}{{/builds_flows}}{{/can_write_draft}}{{#can_run_preview}}\n- A request to run something also goes to the test_run tools. Use run_script, run_flow or run_agent only when the user asks for the deployed version, after reading it with version \"deployed\" so the arguments match.{{/can_run_preview}}{{^can_run_preview}}{{#can_run_flow_preview}}\n- A request to run a flow or agent also goes to test_run_flow or test_run_agent, which run the draft. Use run_flow or run_agent only when the user asks for the deployed version, and run_script for any script: those run the DEPLOYED item as this user, so read it with read_workspace_item version \"deployed\" first so the arguments match.{{/can_run_flow_preview}}{{^can_run_flow_preview}}{{#runs}}\n- run_script, run_flow and run_agent are how you run anything here: they run the DEPLOYED item as this user. Read it with read_workspace_item version \"deployed\" first so the arguments match.{{/runs}}{{/can_run_flow_preview}}{{/can_run_preview}}{{#can_write_any_draft}}\n- To undo your own work, discard its draft with discard_local_draft.{{#can_deploy_any_kind}} delete_workspace_item removes an item that is deployed.{{/can_deploy_any_kind}}{{/can_write_any_draft}}{{^can_write_any_draft}}{{^read_only}}\n- You cannot create or edit anything, but where the server allows it discard_local_draft drops a draft this user left behind, deploy_workspace_item deploys one when the user asks, and delete_workspace_item removes a deployed item.{{/read_only}}{{/can_write_any_draft}}{{^read_only}}{{#unmanaged}}\n- This workspace does not let this user change {{unmanaged_kinds}}, here or in Windmill: suggest asking a workspace admin.{{/unmanaged}}{{/read_only}}\n- Listings return only what this user can see. When an item they name is missing, say it may be in a folder they cannot read, not that it does not exist.\n- No one can read a variable's value through these tools.{{#can_draft_variables}} When editing a variable, pass only the fields that change.{{/can_draft_variables}}{{#can_write_draft}}\n- Before writing code against a third-party API, look for its integration with search_hub_scripts and get_hub_integration.{{/can_write_draft}}\n- {{#can_write_app_draft}}Only raw apps (`rawApp` true) can be read, edited and deployed here. When a deploy says it widens who may open an app, tell the user in plain words.{{/can_write_app_draft}}{{^can_write_app_draft}}Only raw apps (`rawApp` true) can be read here.{{/can_write_app_draft}}\n- Datatables are set up in the workspace settings. Start from list_datatables; one with `migrations_enabled` changes its schema through migrations only.{{#can_draft_resources}}{{#can_create_resource_type}}\n- create_resource_type adds a resource type: show the user the schema first and create it once they agree.{{/can_create_resource_type}}{{^can_create_resource_type}}\n- This user cannot create a resource type here, since the workspace refuses their direct deployment: when one is needed, give them its name and JSON Schema to pass to a workspace admin.{{/can_create_resource_type}}{{/can_draft_resources}}\n- For how Windmill itself works, use search_docs and read_docs_page, and link the page you relied on.{{#can_write_any_draft}}\n\nPath conventions:\n- A workspace path starts with one of two namespaces; its trailing <name> may itself contain \"/\", so a path has three or more segments:\n - `u/{{username}}/<name>` — your personal scope. Default for ad-hoc, exploratory, or scratch work.\n - `f/<folder>/<name>` — a shared folder scope; the <folder> must already exist (a bare `f/<name>` with no folder segment is INVALID and will fail).\n- If the user supplies a fully qualified `f/<folder>/...` path, use that exact path; they have already chosen the folder. Do not ask for folder confirmation or substitute a `u/{{username}}/...` path unless a tool rejects it.\n- Default a bare name with no namespace prefix (e.g. \"create a flow called myflow\") to `u/{{username}}/<name>`. Never invent an `f/<folder>/...` path for a folder that does not exist{{#can_create_folder}}; create one with `create_folder` only when the user explicitly asks for a new folder{{/can_create_folder}}.{{folder_guidance}}{{/can_write_any_draft}}{{#can_create_folder}}{{^can_write_any_draft}}\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.{{/can_write_any_draft}}{{/can_create_folder}}", + "template": "This server works in a Windmill workspace as the user \"{{username}}\".{{#read_only}}{{#runs_deployed}}\n\nThis connection can read the workspace's items, runs and data, and run scripts, flows and agents that are already deployed. It cannot create, edit, deploy or delete anything, nor test-run code that is not deployed: when the user asks for such a change, say plainly that this connection cannot make it, rather than describing steps as if you had made it.{{/runs_deployed}}{{^runs_deployed}}\n\nThis connection is read-only: it can read the workspace's items, runs and data, but cannot run, create, edit, deploy or delete anything. When the user asks for a run or a change, say plainly that this connection cannot make it, rather than describing steps as if you had made it.{{/runs_deployed}}{{/read_only}}{{^read_only}}{{^can_write_draft}}\n\nThis user's role does not let them create or edit {{refused_kinds}} here, so when they ask for such a change, say plainly that you cannot make it rather than describing steps as if you had, and suggest asking a workspace admin, who can grant their role more.{{#builds_flows}} Their role does let them compose flows out of scripts and flows that are already deployed: write flows with write_flow and patch_flow_json, every step calling a deployed script or flow by path. The server refuses inline code anywhere in the flow, so when a flow needs logic no deployed script provides, say so and suggest asking a workspace admin for that script.{{/builds_flows}}{{#builds_apps}} Their role does let them build raw apps whose backend runnables are path runnables to deployed scripts or flows; call get_instructions with subject \"app\" first. The server refuses inline and hub runnables, and runs an app they deploy sandboxed, as the user who deployed it.{{/builds_apps}}{{#has_draft_tools}} They can draft with {{draft_tools}}.{{/has_draft_tools}}{{/can_write_draft}}{{/read_only}}\n\nRules:{{#can_write_any_draft}}\n- What you write is a per-user draft, saved server-side and visible only to this user. {{#can_deploy}}Nothing reaches the workspace until deploy_workspace_item deploys it, which you call only when the user asks.{{/can_deploy}}{{^can_deploy}}{{#can_deploy_any_kind}}Nothing reaches the workspace until it is deployed, and this workspace's deploy rules let this user deploy only the schedules and triggers their role manages: call deploy_workspace_item for those only when the user asks, and for anything else give them the draft's link and say it needs deploying by someone allowed to.{{/can_deploy_any_kind}}{{^can_deploy_any_kind}}Nothing reaches the workspace until it is deployed, which this workspace's deploy rules do not let this user do: when a draft is ready, give them its link and say it needs deploying by someone allowed to.{{/can_deploy_any_kind}}{{/can_deploy}}{{/can_write_any_draft}}\n{{#can_write_any_draft}}- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, a draft's editor (`url`), an app draft's editor with its live preview (`preview_url`), a deployed item's page. Whenever the user will want to see what you built or ran, or has to do a step in Windmill themselves: show it with show_run, show_runs, show_item or show_deploy_review when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link.{{/can_write_any_draft}}{{^can_write_any_draft}}- The user sees no Windmill page next to this conversation. Tool results carry links instead: a run's page, an item's page. Whenever the user will want to see what you found{{#runs}} or ran{{/runs}}, or has to do a step in Windmill themselves: show it with show_run, show_runs or show_item when you have them (each card carries the link), otherwise open the link in a browser the user can see if you have one, and otherwise give the link.{{/can_write_any_draft}}\n- Find items with list_workspace_items and read one with read_workspace_item{{#can_write_any_draft}} before changing it{{/can_write_any_draft}}. An agent is a resource of type `ai_agent`{{#runs}}: {{#can_run_flow_preview}}test it with test_run_agent and {{/can_run_flow_preview}}run a deployed one with run_agent, never run_flow or run_script.{{/runs}}{{^runs}}.{{/runs}}{{#can_run_preview}}\n- When the user asks for something done against the systems the workspace connects to, rather than for building an item, do it with code: look for a saved script that does it first (list_workspace_items with a query), else run code with test_run_code and, once it worked, offer to keep it as a script with write_script. get_instructions with subject \"code_mode\" has the details.{{/can_run_preview}}{{#can_write_draft}}\n- Call get_instructions before writing a script, flow, agent, resource or app, a data pipeline or a datatable migration. For a script, pass its language.{{#can_draft_triggers}} Call get_trigger_schema before write_trigger, since each trigger kind takes different fields, and{{/can_draft_triggers}}{{^can_draft_triggers}} Call{{/can_draft_triggers}} get_db_schema before writing SQL against a database resource.{{/can_write_draft}}{{^can_write_draft}}{{#can_draft_resources}}\n- Call get_instructions before writing a resource.{{#can_draft_triggers}} Call get_trigger_schema before write_trigger, since each trigger kind takes different fields.{{/can_draft_triggers}}{{/can_draft_resources}}{{/can_write_draft}}{{#can_write_draft}}{{#can_run_preview}}\n- After writing a script, flow, agent or app runnable, test it with test_run_script, test_run_flow, test_run_step, test_run_agent or test_run_app_runnable before saying it works. They run the draft, so nothing needs deploying.{{/can_run_preview}}{{/can_write_draft}}{{^can_write_draft}}{{#builds_flows}}{{#can_run_flow_preview}}\n- After writing a flow, test it with test_run_flow before saying it works. It runs the draft, so nothing needs deploying.{{/can_run_flow_preview}}{{/builds_flows}}{{/can_write_draft}}{{#can_run_preview}}\n- A request to run something also goes to the test_run tools. Use run_script, run_flow or run_agent only when the user asks for the deployed version, after reading it with version \"deployed\" so the arguments match.{{/can_run_preview}}{{^can_run_preview}}{{#can_run_flow_preview}}\n- A request to run a flow or agent also goes to test_run_flow or test_run_agent, which run the draft. Use run_flow or run_agent only when the user asks for the deployed version, and run_script for any script: those run the DEPLOYED item as this user, so read it with read_workspace_item version \"deployed\" first so the arguments match.{{/can_run_flow_preview}}{{^can_run_flow_preview}}{{#runs}}\n- run_script, run_flow and run_agent are how you run anything here: they run the DEPLOYED item as this user. Read it with read_workspace_item version \"deployed\" first so the arguments match.{{/runs}}{{/can_run_flow_preview}}{{/can_run_preview}}{{#can_write_any_draft}}\n- To undo your own work, discard its draft with discard_local_draft.{{#can_deploy_any_kind}} delete_workspace_item removes an item that is deployed.{{/can_deploy_any_kind}}{{/can_write_any_draft}}{{^can_write_any_draft}}{{^read_only}}\n- You cannot create or edit anything, but where the server allows it discard_local_draft drops a draft this user left behind, deploy_workspace_item deploys one when the user asks, and delete_workspace_item removes a deployed item.{{/read_only}}{{/can_write_any_draft}}{{^read_only}}{{#unmanaged}}\n- This workspace does not let this user change {{unmanaged_kinds}}, here or in Windmill: suggest asking a workspace admin.{{/unmanaged}}{{/read_only}}\n- Listings return only what this user can see. When an item they name is missing, say it may be in a folder they cannot read, not that it does not exist.\n- No one can read a variable's value through these tools.{{#can_draft_variables}} When editing a variable, pass only the fields that change.{{/can_draft_variables}}{{#can_write_draft}}\n- Before writing code against a third-party API, look for its integration with search_hub_scripts and get_hub_integration.{{/can_write_draft}}\n- {{#can_write_app_draft}}Only raw apps (`rawApp` true) can be read, edited and deployed here. When a deploy says it widens who may open an app, tell the user in plain words.{{/can_write_app_draft}}{{^can_write_app_draft}}Only raw apps (`rawApp` true) can be read here.{{/can_write_app_draft}}\n- Datatables are set up in the workspace settings. Start from list_datatables; one with `migrations_enabled` changes its schema through migrations only.{{#can_draft_resources}}{{#can_create_resource_type}}\n- create_resource_type adds a resource type: show the user the schema first and create it once they agree.{{/can_create_resource_type}}{{^can_create_resource_type}}\n- This user cannot create a resource type here, since the workspace refuses their direct deployment: when one is needed, give them its name and JSON Schema to pass to a workspace admin.{{/can_create_resource_type}}{{/can_draft_resources}}\n- For how Windmill itself works, use search_docs and read_docs_page, and link the page you relied on.{{#can_write_any_draft}}\n\nPath conventions:\n- A workspace path starts with one of two namespaces; its trailing <name> may itself contain \"/\", so a path has three or more segments:\n - `u/{{username}}/<name>` — your personal scope. Default for ad-hoc, exploratory, or scratch work.\n - `f/<folder>/<name>` — a shared folder scope; the <folder> must already exist (a bare `f/<name>` with no folder segment is INVALID and will fail).\n- If the user supplies a fully qualified `f/<folder>/...` path, use that exact path; they have already chosen the folder. Do not ask for folder confirmation or substitute a `u/{{username}}/...` path unless a tool rejects it.\n- Default a bare name with no namespace prefix (e.g. \"create a flow called myflow\") to `u/{{username}}/<name>`. Never invent an `f/<folder>/...` path for a folder that does not exist{{#can_create_folder}}; create one with `create_folder` only when the user explicitly asks for a new folder{{/can_create_folder}}.{{folder_guidance}}{{/can_write_any_draft}}{{#can_create_folder}}{{^can_write_any_draft}}\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.{{/can_write_any_draft}}{{/can_create_folder}}", "profiles": { "read_only": { "flags": "read_only unmanaged", @@ -887,44 +887,44 @@ "rendered_sha256": { "read_only": "a2a002ef12a3714f73938b5451482d5e226144c10f4f3bc09495f6f886dd3624", "read_run": "b1dccd011a0bab7180e949e60f3637759e36dc167a99684c3e76e0d21666f827", - "full:11:1:full:full:11": "355657292e125e8a75df0cb0a08da64ae5e268f80682328adf706abf573a27cc", - "full:10:1:full:full:11": "d9f688a012c6c75ed811cae1215a3472ddb94bf018edb4f452585ed5c08f5815", - "full:01:1:none:none:11": "b7ac91e039c925eb34c58b8fb9a8c6840cd7eac5ab8eb91b35e44ea1cdfd3fbd", - "full:01:1:none:none:10": "a46e98609c159e1ece181e61e14e4180cfa619797fd638ce64080673c6c24119", - "full:01:1:none:none:01": "8bb8ee7c586040e15a43503c29fabe43852ee33d66288f6d35c37dd377d29540", - "full:01:1:none:none:00": "9f3b6d19101c7d644c2c8a8b0f6b75d2c45dd66e9360ef900ab48d610ff90a95", - "full:01:1:none:compose:11": "dafeeeb951a5a05441c555201081a510ea349d76fd65fa4a646222c7f31c62e0", - "full:01:1:none:compose:10": "dffa6d8f7e14b88eb763f8f52d4979a48620c50e09eb8bca6bc364945c6317e8", - "full:01:1:none:compose:01": "ef16520047e87d643618f36070cf255a4c3f0c9a7a6ca0d880225906e70dbd6f", - "full:01:1:none:compose:00": "8570d394f70635233118a2bbb70b3c035ffd26414034f484909cfd459d5e88f5", - "full:01:1:none:full:11": "dafeeeb951a5a05441c555201081a510ea349d76fd65fa4a646222c7f31c62e0", - "full:01:1:none:full:10": "dffa6d8f7e14b88eb763f8f52d4979a48620c50e09eb8bca6bc364945c6317e8", - "full:01:1:none:full:01": "ef16520047e87d643618f36070cf255a4c3f0c9a7a6ca0d880225906e70dbd6f", - "full:01:1:none:full:00": "8570d394f70635233118a2bbb70b3c035ffd26414034f484909cfd459d5e88f5", - "full:01:1:compose:none:11": "9f4ec78b6eb9ec845fe558ddb7cbf0047d5ac41ece2b4f1060585d34ab5873aa", - "full:01:1:compose:none:10": "404cbac8cdcfdea36f336a675fbb6ed81ee00e6f540b0970691b1b91080ce853", - "full:01:1:compose:none:01": "b276d7a4b1bec12b0f0b3a002c8bc291c51c00095afb287d9cddf703db91b3ed", - "full:01:1:compose:none:00": "4728593a56fe37c6f2f0108ae76a444494ef3b9b7d08178ca919dfe42f405044", - "full:01:1:compose:compose:11": "355657292e125e8a75df0cb0a08da64ae5e268f80682328adf706abf573a27cc", - "full:01:1:compose:compose:10": "3174c7d16f4083f73da28975dee940e878cef65374cbc8cca83ed0a4fe7782f3", - "full:01:1:compose:compose:01": "3e02173263aa85dc0806faf4fafc17154347082a3aa2ef7787f567bddf7396ff", - "full:01:1:compose:compose:00": "92b5eba68f5b838927b4da52584277c7694a7e7b660662c607db1bcae03b0d09", - "full:01:1:compose:full:11": "355657292e125e8a75df0cb0a08da64ae5e268f80682328adf706abf573a27cc", - "full:01:1:compose:full:10": "3174c7d16f4083f73da28975dee940e878cef65374cbc8cca83ed0a4fe7782f3", - "full:01:1:compose:full:01": "3e02173263aa85dc0806faf4fafc17154347082a3aa2ef7787f567bddf7396ff", - "full:01:1:compose:full:00": "92b5eba68f5b838927b4da52584277c7694a7e7b660662c607db1bcae03b0d09", - "full:01:1:full:none:11": "9f4ec78b6eb9ec845fe558ddb7cbf0047d5ac41ece2b4f1060585d34ab5873aa", - "full:01:1:full:none:10": "404cbac8cdcfdea36f336a675fbb6ed81ee00e6f540b0970691b1b91080ce853", - "full:01:1:full:none:01": "b276d7a4b1bec12b0f0b3a002c8bc291c51c00095afb287d9cddf703db91b3ed", - "full:01:1:full:none:00": "4728593a56fe37c6f2f0108ae76a444494ef3b9b7d08178ca919dfe42f405044", - "full:01:1:full:compose:11": "355657292e125e8a75df0cb0a08da64ae5e268f80682328adf706abf573a27cc", - "full:01:1:full:compose:10": "3174c7d16f4083f73da28975dee940e878cef65374cbc8cca83ed0a4fe7782f3", - "full:01:1:full:compose:01": "3e02173263aa85dc0806faf4fafc17154347082a3aa2ef7787f567bddf7396ff", - "full:01:1:full:compose:00": "92b5eba68f5b838927b4da52584277c7694a7e7b660662c607db1bcae03b0d09", - "full:01:1:full:full:11": "355657292e125e8a75df0cb0a08da64ae5e268f80682328adf706abf573a27cc", - "full:01:1:full:full:10": "3174c7d16f4083f73da28975dee940e878cef65374cbc8cca83ed0a4fe7782f3", - "full:01:1:full:full:01": "3e02173263aa85dc0806faf4fafc17154347082a3aa2ef7787f567bddf7396ff", - "full:01:1:full:full:00": "92b5eba68f5b838927b4da52584277c7694a7e7b660662c607db1bcae03b0d09", + "full:11:1:full:full:11": "6b96eb1058aab08349cdefbd7ad11e67449b92b7b2696ab6c074bec2fef13e8b", + "full:10:1:full:full:11": "827a11412a41d2da5d4a8537fa460d4387a7ffd042d581df457f13610043c9f5", + "full:01:1:none:none:11": "56f2dc9cdc1e694826715076eb94d6441a3462585a8bb1ff3debcb9aed51b0f4", + "full:01:1:none:none:10": "9932459c899b37f7c160818ab9cd06cc1feed5fe1e64432a3e64656aa032b02d", + "full:01:1:none:none:01": "cd8b075e561da3bf5071170a40bcd1c64797a33f0ff1f8fe26a68f7921eff864", + "full:01:1:none:none:00": "6771b63c3fc122c349a2e9b4e65f08371c3bd929147744dbefe90e67d7d95ffd", + "full:01:1:none:compose:11": "585f2679e2bdcb15a151d629c6a1626a55109e9ccefcb15ea053f9b1c54b0f20", + "full:01:1:none:compose:10": "a0b9521f2aa0372f9008e8101ad768e4ebd1e95a803a9b6ee3957d730ec4e240", + "full:01:1:none:compose:01": "8a833a5cd8dab2f2251cec5d4f83a6379791830460c866431b9edb5b988751bd", + "full:01:1:none:compose:00": "ff27653a0e6b9f43407c1ebb0304da83b047892e27023092d44b8a5be96e8140", + "full:01:1:none:full:11": "585f2679e2bdcb15a151d629c6a1626a55109e9ccefcb15ea053f9b1c54b0f20", + "full:01:1:none:full:10": "a0b9521f2aa0372f9008e8101ad768e4ebd1e95a803a9b6ee3957d730ec4e240", + "full:01:1:none:full:01": "8a833a5cd8dab2f2251cec5d4f83a6379791830460c866431b9edb5b988751bd", + "full:01:1:none:full:00": "ff27653a0e6b9f43407c1ebb0304da83b047892e27023092d44b8a5be96e8140", + "full:01:1:compose:none:11": "2b92fb20c609678429a38ca8ed5fb6f2dd6631b5aa05b7e3ea64d3eadcb35f18", + "full:01:1:compose:none:10": "208386afbd6605dbdf1d2b0471f9547ff34a19491927df12dfaa74f4acd9040b", + "full:01:1:compose:none:01": "acf1063d5964f61e6ba2943b06727dc7b97e30fa3742c1030b84b70360e7a787", + "full:01:1:compose:none:00": "8e61f4f27a6fc8cde669afb2d65927e89ea13974a8a1878103ead7f15f4e75b5", + "full:01:1:compose:compose:11": "6b96eb1058aab08349cdefbd7ad11e67449b92b7b2696ab6c074bec2fef13e8b", + "full:01:1:compose:compose:10": "e0fcdc4eef17305afa2f14f35534c246efd6a9510e5af604f40e48a9eb89d1e5", + "full:01:1:compose:compose:01": "1843039bd39e5b0def916c838ac8f0b2d8778a4f9d15face0031da8618066cf1", + "full:01:1:compose:compose:00": "456471d15cf59e2507aa454457fa02eee6bd1565aae9a83a16aba73675d11028", + "full:01:1:compose:full:11": "6b96eb1058aab08349cdefbd7ad11e67449b92b7b2696ab6c074bec2fef13e8b", + "full:01:1:compose:full:10": "e0fcdc4eef17305afa2f14f35534c246efd6a9510e5af604f40e48a9eb89d1e5", + "full:01:1:compose:full:01": "1843039bd39e5b0def916c838ac8f0b2d8778a4f9d15face0031da8618066cf1", + "full:01:1:compose:full:00": "456471d15cf59e2507aa454457fa02eee6bd1565aae9a83a16aba73675d11028", + "full:01:1:full:none:11": "2b92fb20c609678429a38ca8ed5fb6f2dd6631b5aa05b7e3ea64d3eadcb35f18", + "full:01:1:full:none:10": "208386afbd6605dbdf1d2b0471f9547ff34a19491927df12dfaa74f4acd9040b", + "full:01:1:full:none:01": "acf1063d5964f61e6ba2943b06727dc7b97e30fa3742c1030b84b70360e7a787", + "full:01:1:full:none:00": "8e61f4f27a6fc8cde669afb2d65927e89ea13974a8a1878103ead7f15f4e75b5", + "full:01:1:full:compose:11": "6b96eb1058aab08349cdefbd7ad11e67449b92b7b2696ab6c074bec2fef13e8b", + "full:01:1:full:compose:10": "e0fcdc4eef17305afa2f14f35534c246efd6a9510e5af604f40e48a9eb89d1e5", + "full:01:1:full:compose:01": "1843039bd39e5b0def916c838ac8f0b2d8778a4f9d15face0031da8618066cf1", + "full:01:1:full:compose:00": "456471d15cf59e2507aa454457fa02eee6bd1565aae9a83a16aba73675d11028", + "full:01:1:full:full:11": "6b96eb1058aab08349cdefbd7ad11e67449b92b7b2696ab6c074bec2fef13e8b", + "full:01:1:full:full:10": "e0fcdc4eef17305afa2f14f35534c246efd6a9510e5af604f40e48a9eb89d1e5", + "full:01:1:full:full:01": "1843039bd39e5b0def916c838ac8f0b2d8778a4f9d15face0031da8618066cf1", + "full:01:1:full:full:00": "456471d15cf59e2507aa454457fa02eee6bd1565aae9a83a16aba73675d11028", "full:01:0:none:none:11": "6e298c3aa2c213e11284300395cffa5a50973c08ca99217a8527dac29a1edc39", "full:01:0:none:none:10": "dc91d71b9d073ed7373719375889d3decad8ea8edb55f74592ab743d310c03f0", "full:01:0:none:none:01": "1d57273309c06e5d471da0abf3fe20413766a4e9ec4b4a8844f44a8fee5ea41b", @@ -941,42 +941,42 @@ "full:01:0:compose:compose:10": "5ea1a20c7f9b390d9bc3e4edc91529387876b7c547bee4a75472979f58c8f0cb", "full:01:0:compose:compose:01": "b3d9ef9882e8d4e17e7899403ab0184c1313d003eebab4de6cf41b59819e2ebb", "full:01:0:compose:compose:00": "f2c815c82abccfdcbf8a6e3c39b17c9a7cbe08db32e531b84cc0f1ae91655335", - "full:00:1:none:none:11": "ef4a2f66bd05eb22d92c6a88e5caf83d1a8b02db560db96ccc23755e8fd6d8d9", - "full:00:1:none:none:10": "fbb85e9d0036b16025b318ce9ace58d5a163ab0ceeaed918bfbf3b1ab0e93d6f", - "full:00:1:none:none:01": "c5bc889a27124519592086f0f94c8313d9ba8a225a50bf16bbb5bb04212f2952", - "full:00:1:none:none:00": "584f5d9dcfc95669518e1516e9c282b357024ee24be31047b97cbc035e1cd792", - "full:00:1:none:compose:11": "767778374b9da9e43adac84e9a19ea90100f1f1eef6abaca33476b332aa29081", - "full:00:1:none:compose:10": "7ae0803c0c47dd8199ad30dbfacae40669bf6e5eb0eed046904b583cf9a3888f", - "full:00:1:none:compose:01": "5ca874234ce2a52816e908e8e6b7363c3fe45651702eb4b219151589e5de7977", - "full:00:1:none:compose:00": "b37c3e7542d716546db196aa8358e8a0ef8e52dc37b50fbb57f62862d45fde23", - "full:00:1:none:full:11": "767778374b9da9e43adac84e9a19ea90100f1f1eef6abaca33476b332aa29081", - "full:00:1:none:full:10": "7ae0803c0c47dd8199ad30dbfacae40669bf6e5eb0eed046904b583cf9a3888f", - "full:00:1:none:full:01": "5ca874234ce2a52816e908e8e6b7363c3fe45651702eb4b219151589e5de7977", - "full:00:1:none:full:00": "b37c3e7542d716546db196aa8358e8a0ef8e52dc37b50fbb57f62862d45fde23", - "full:00:1:compose:none:11": "49165f1bbd9e26bc1bb0b32b14bab96c2daa50f816332806c2521b8d46b9134e", - "full:00:1:compose:none:10": "d77d7a0566f596c8ba3d34967e490d735618e5b1df95e9984d268b70fc44c432", - "full:00:1:compose:none:01": "d3c04033a12757b8b6ced60290084f3ac75344e36a770d6f093c68ac2c0773ad", - "full:00:1:compose:none:00": "7d4511f33441526e5653c0a0892fb7aa232b8890c7268eff7cd43ab5c3e6d0ec", - "full:00:1:compose:compose:11": "d9f688a012c6c75ed811cae1215a3472ddb94bf018edb4f452585ed5c08f5815", - "full:00:1:compose:compose:10": "b7e5f39b2086df783b656a4acea6ab24cc3bdde161f740668ee12ed9beaf28b8", - "full:00:1:compose:compose:01": "b494bcc24ae2e6151df360fb37dc17963df500e2ae82cef065ad7b36045c5492", - "full:00:1:compose:compose:00": "ed4b08a13b7f4efa79611eaa15b8a923c9d8447cf109b5097e871ff23f19e8b0", - "full:00:1:compose:full:11": "d9f688a012c6c75ed811cae1215a3472ddb94bf018edb4f452585ed5c08f5815", - "full:00:1:compose:full:10": "b7e5f39b2086df783b656a4acea6ab24cc3bdde161f740668ee12ed9beaf28b8", - "full:00:1:compose:full:01": "b494bcc24ae2e6151df360fb37dc17963df500e2ae82cef065ad7b36045c5492", - "full:00:1:compose:full:00": "ed4b08a13b7f4efa79611eaa15b8a923c9d8447cf109b5097e871ff23f19e8b0", - "full:00:1:full:none:11": "49165f1bbd9e26bc1bb0b32b14bab96c2daa50f816332806c2521b8d46b9134e", - "full:00:1:full:none:10": "d77d7a0566f596c8ba3d34967e490d735618e5b1df95e9984d268b70fc44c432", - "full:00:1:full:none:01": "d3c04033a12757b8b6ced60290084f3ac75344e36a770d6f093c68ac2c0773ad", - "full:00:1:full:none:00": "7d4511f33441526e5653c0a0892fb7aa232b8890c7268eff7cd43ab5c3e6d0ec", - "full:00:1:full:compose:11": "d9f688a012c6c75ed811cae1215a3472ddb94bf018edb4f452585ed5c08f5815", - "full:00:1:full:compose:10": "b7e5f39b2086df783b656a4acea6ab24cc3bdde161f740668ee12ed9beaf28b8", - "full:00:1:full:compose:01": "b494bcc24ae2e6151df360fb37dc17963df500e2ae82cef065ad7b36045c5492", - "full:00:1:full:compose:00": "ed4b08a13b7f4efa79611eaa15b8a923c9d8447cf109b5097e871ff23f19e8b0", - "full:00:1:full:full:11": "d9f688a012c6c75ed811cae1215a3472ddb94bf018edb4f452585ed5c08f5815", - "full:00:1:full:full:10": "b7e5f39b2086df783b656a4acea6ab24cc3bdde161f740668ee12ed9beaf28b8", - "full:00:1:full:full:01": "b494bcc24ae2e6151df360fb37dc17963df500e2ae82cef065ad7b36045c5492", - "full:00:1:full:full:00": "ed4b08a13b7f4efa79611eaa15b8a923c9d8447cf109b5097e871ff23f19e8b0", + "full:00:1:none:none:11": "c2a8683bd89eeb2af4144bfd5529447e7e4dc0e82b4dd77cf194d6b721865f7f", + "full:00:1:none:none:10": "ff424218521348cdea10160e74bc74f043656608a1b8b0575bbef945764a292e", + "full:00:1:none:none:01": "8f2e89f8a9f9d48ba52464acf105939af60d29bdb3cbf44bbf52767a1b3a7b44", + "full:00:1:none:none:00": "d284fca767d795a9ee77bc04075f69d7b2ae32343144227ed0b932eb3bd2f7f7", + "full:00:1:none:compose:11": "b6502094c8164041311ad9bbbfa08a71ba31a436ac95bd85bff53163b39c381d", + "full:00:1:none:compose:10": "9e15044c0f3e33795ca946102b4740bae18e7a6f0a78caa117cab693919ed2ff", + "full:00:1:none:compose:01": "86c0ba117eaa08b9298c81a6509f3a3a4dffcc1eb59c36b37202044d6c4dcc1e", + "full:00:1:none:compose:00": "a456236a3939e332f6c6afe6b0c034b05aaae129141c506c56f62ad13e0d007f", + "full:00:1:none:full:11": "b6502094c8164041311ad9bbbfa08a71ba31a436ac95bd85bff53163b39c381d", + "full:00:1:none:full:10": "9e15044c0f3e33795ca946102b4740bae18e7a6f0a78caa117cab693919ed2ff", + "full:00:1:none:full:01": "86c0ba117eaa08b9298c81a6509f3a3a4dffcc1eb59c36b37202044d6c4dcc1e", + "full:00:1:none:full:00": "a456236a3939e332f6c6afe6b0c034b05aaae129141c506c56f62ad13e0d007f", + "full:00:1:compose:none:11": "9b2e8c8998f5b1d74ca4e81075426a920b791f82b238fae31bd9cf9b414173a2", + "full:00:1:compose:none:10": "9ac5f04a542d1c00bbfed4bc96c77ed60097052962e616b0f2a85b0650be5ee7", + "full:00:1:compose:none:01": "5432d7d60e135eaa648dda95cab5a1dc0659d8344deef6946ac2c23b74002675", + "full:00:1:compose:none:00": "ee728ec68da0479f894dfa732149a4483b02a3dc1c2306f6ca18ae5c1586bab8", + "full:00:1:compose:compose:11": "827a11412a41d2da5d4a8537fa460d4387a7ffd042d581df457f13610043c9f5", + "full:00:1:compose:compose:10": "87b1cd9fe77fbf1aee76f121ed54ae488d1efc8e622d5b247440c134c85fef2e", + "full:00:1:compose:compose:01": "3e8a0ff1d4643f62514fbc8dac721f946772bb49381a14007bcce419ebb3c0cd", + "full:00:1:compose:compose:00": "d714e81fec0d4015a9798a929d52ace788dbf3fa6fd5597b8141163814111f57", + "full:00:1:compose:full:11": "827a11412a41d2da5d4a8537fa460d4387a7ffd042d581df457f13610043c9f5", + "full:00:1:compose:full:10": "87b1cd9fe77fbf1aee76f121ed54ae488d1efc8e622d5b247440c134c85fef2e", + "full:00:1:compose:full:01": "3e8a0ff1d4643f62514fbc8dac721f946772bb49381a14007bcce419ebb3c0cd", + "full:00:1:compose:full:00": "d714e81fec0d4015a9798a929d52ace788dbf3fa6fd5597b8141163814111f57", + "full:00:1:full:none:11": "9b2e8c8998f5b1d74ca4e81075426a920b791f82b238fae31bd9cf9b414173a2", + "full:00:1:full:none:10": "9ac5f04a542d1c00bbfed4bc96c77ed60097052962e616b0f2a85b0650be5ee7", + "full:00:1:full:none:01": "5432d7d60e135eaa648dda95cab5a1dc0659d8344deef6946ac2c23b74002675", + "full:00:1:full:none:00": "ee728ec68da0479f894dfa732149a4483b02a3dc1c2306f6ca18ae5c1586bab8", + "full:00:1:full:compose:11": "827a11412a41d2da5d4a8537fa460d4387a7ffd042d581df457f13610043c9f5", + "full:00:1:full:compose:10": "87b1cd9fe77fbf1aee76f121ed54ae488d1efc8e622d5b247440c134c85fef2e", + "full:00:1:full:compose:01": "3e8a0ff1d4643f62514fbc8dac721f946772bb49381a14007bcce419ebb3c0cd", + "full:00:1:full:compose:00": "d714e81fec0d4015a9798a929d52ace788dbf3fa6fd5597b8141163814111f57", + "full:00:1:full:full:11": "827a11412a41d2da5d4a8537fa460d4387a7ffd042d581df457f13610043c9f5", + "full:00:1:full:full:10": "87b1cd9fe77fbf1aee76f121ed54ae488d1efc8e622d5b247440c134c85fef2e", + "full:00:1:full:full:01": "3e8a0ff1d4643f62514fbc8dac721f946772bb49381a14007bcce419ebb3c0cd", + "full:00:1:full:full:00": "d714e81fec0d4015a9798a929d52ace788dbf3fa6fd5597b8141163814111f57", "full:00:0:none:none:11": "636f56186fb922e1d8a0a2eb2e47ffcb50dffbc5ede80d1cd6070c31f0ba5d6f", "full:00:0:none:none:10": "7107bcee6ec708a56bb154d6126a5fc50ee06c12f9b08601f4b916861e97bdf3", "full:00:0:none:none:01": "c2f6200dfb97afd78860fe1d38a49992f177a5565d2ffd7bdf846c9c5116eeb5", diff --git a/backend/windmill-api/src/ai_session_tools/gen/tools.json b/backend/windmill-api/src/ai_session_tools/gen/tools.json index 81b779088f..a9247dfcee 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/tools.json +++ b/backend/windmill-api/src/ai_session_tools/gen/tools.json @@ -216,7 +216,7 @@ "type": "object", "properties": { "subject": { - "description": "What to get authoring instructions for: a workspace item type (script, flow, resource, app), \"agent\" for a saved AI agent (an `ai_agent` resource, as the Agents page lists it), \"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.", + "description": "What to get authoring instructions for: a workspace item type (script, flow, resource, app), \"agent\" for a saved AI agent (an `ai_agent` resource, as the Agents page lists it), \"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, \"workspace_settings\" for the keys and rules of the workspace settings (admins only), \"display\" for the tables and charts a return value renders as, or \"code_mode\" for doing a task the user asks for against the systems the workspace connects to by running code, then saving it to reuse. Schedules, triggers, and variables don't need instructions — their tool schemas describe everything.", "type": "string", "enum": [ "script", @@ -226,7 +226,9 @@ "agent", "datatable", "pipeline", - "workspace_settings" + "workspace_settings", + "display", + "code_mode" ] }, "language": { @@ -463,7 +465,7 @@ } }, "query": { - "description": "Optional case-insensitive path or summary search string.", + "description": "Optional search words matched against path and summary. Scripts and flows are searched across the whole workspace, every word in any order; other types are filtered by the whole string.", "type": "string" }, "path_prefix": { @@ -1053,6 +1055,51 @@ }, "read_only": false }, + { + "name": "test_run_code", + "description": "Run code as a preview job in the workspace, without writing a draft first. To keep code that worked, write it as a script with write_script. It runs with exactly the `args` you send. When the user asked for this run, show it to them with show_run, if you have it.", + "parameters": { + "type": "object", + "properties": { + "code": { + "description": "The whole script: a `main` function whose parameters are its inputs, in the language given.", + "type": "string" + }, + "language": { + "description": "A Windmill script language such as bun, python3 or deno. Defaults to bun.", + "type": "string" + }, + "args": { + "description": "Arguments to pass to the runnable. Omit or pass null when no arguments are needed. An argument typed as a resource (format \"resource-<type>\" in the input schema) takes the bare string \"$res:<path>\" as its whole value — never an object wrapper like {\"$res\": \"<path>\"}, and never a plain path, both of which reach the runnable unresolved. Same for a variable, with \"$var:<path>\". The prefixed string can also sit in a nested field, e.g. {\"gh_auth\": {\"token\": \"$var:g/all/gh_token\"}}. When the input schema carries a top-level \"prompt_for_ai\", it is the author's own instructions for choosing these arguments: follow it.", + "anyOf": [ + { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} + }, + { + "type": "null" + } + ] + }, + "background": { + "description": "Run in the background without waiting. Set true for jobs you expect to be long (deploys, backfills, big queries): the result gives its job id, to follow with get_run. Leave unset for normal runs, which wait briefly and only background automatically if slow.", + "type": "boolean" + }, + "wait_seconds": { + "description": "How many seconds to wait for the job in-turn before it keeps running in the background. Defaults to 15. Raise it (capped at 120) for a job you expect to finish in, say, 30–60s and want the result in this same turn. Ignored when background is true. Do not use this to poll — larger values just hold the turn longer.", + "type": "number" + } + }, + "required": [ + "code" + ], + "additionalProperties": false + }, + "read_only": false + }, { "name": "run_script", "description": "Run a DEPLOYED script for real, under the user's own permissions. It runs with exactly the `args` you send. For a secret argument prefer `$var:<path>` naming an existing workspace variable; a literal also works, but stays in this conversation. 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\"). Then show the run to the user with show_run, if you have it.", diff --git a/backend/windmill-api/src/ai_session_tools/mod.rs b/backend/windmill-api/src/ai_session_tools/mod.rs index 045b87af39..e277168ad5 100644 --- a/backend/windmill-api/src/ai_session_tools/mod.rs +++ b/backend/windmill-api/src/ai_session_tools/mod.rs @@ -154,6 +154,7 @@ const DESTRUCTIVE: &[&str] = &[ "test_run_agent", "test_run_step", "test_run_app_runnable", + "test_run_code", "cancel_job", "exec_datatable_sql", "create_datatable_migration", @@ -180,6 +181,7 @@ const OPEN_WORLD: &[&str] = &[ "test_run_agent", "test_run_step", "test_run_app_runnable", + "test_run_code", "get_db_schema", ]; @@ -400,7 +402,7 @@ impl Ctx<'_> { }; let request = request.body(body).map_err(|e| e.to_string())?; tokio::time::timeout(timeout, async { - let response = router.oneshot(request).await.map_err(|e| e.to_string())?; + let Ok(response) = router.oneshot(request).await; let status = response.status(); let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) .await diff --git a/backend/windmill-api/src/ai_session_tools/runs.rs b/backend/windmill-api/src/ai_session_tools/runs.rs index c3df5f6008..3837bb7468 100644 --- a/backend/windmill-api/src/ai_session_tools/runs.rs +++ b/backend/windmill-api/src/ai_session_tools/runs.rs @@ -14,6 +14,7 @@ use super::{enc, js_head, js_len, js_tail, opt_str_arg, pretty, str_arg, truthy, pub(super) const TOOLS: &[&str] = &[ "test_run_script", + "test_run_code", "run_script", "test_run_flow", "run_flow", @@ -28,6 +29,7 @@ pub(super) const TOOLS: &[&str] = &[ pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult { match name { "test_run_script" => test_run_script(ctx, args).await, + "test_run_code" => test_run_code(ctx, args).await, "run_script" => run_deployed(ctx, args, false).await, "test_run_flow" => test_run_flow(ctx, args).await, "run_flow" => run_deployed(ctx, args, true).await, @@ -982,6 +984,65 @@ async fn test_run_script(ctx: &Ctx<'_>, args: &Value) -> ToolResult { .await } +fn resolve_code(args: &Value) -> Result<Resolved, String> { + let code = str_arg(args, "code")?; + let language = opt_str_arg(args, "language").unwrap_or("bun"); + Ok(Resolved { + schema: None, + code: Some(code.to_string()), + lang: Some(language.to_string()), + summary: None, + runnable_kind: "script", + start_message: "Running code...".to_string(), + conversational: false, + module: None, + target: RunTarget::ScriptPreview { + path: None, + language: language.to_string(), + content: code.to_string(), + preprocessor: false, + }, + }) +} + +/// Code run as a preview job with no item behind it. +async fn test_run_code(ctx: &Ctx<'_>, args: &Value) -> ToolResult { + run_tool( + ctx, + args, + async { resolve_code(args) }, + async |resolved: Resolved| { + let (code, lang) = ( + resolved.code.clone().unwrap_or_default(), + resolved.lang.clone().unwrap_or_default(), + ); + let schema = infer_script_schema(&lang, &code, None, None); + let prepared = + match prepare_args(ctx, "code", proposed_args(args), schema.as_ref(), "code").await + { + Ok(prepared) => prepared, + Err(message) => return Ok(message), + }; + let started = start_run( + ctx, + &resolved.target, + prepared.args, + &form_keys(schema.as_ref()), + ) + .await; + if started.is_ok() { + windmill_common::feature_usage::log_feature_usage( + "code_mode", + "program_run", + &lang, + ); + } + conclude(ctx, args, prepared.notes, started, "code", false, "test").await + }, + ) + .await +} + /// `run_script` and `run_flow`: the deployed item, whatever draft sits on top of it. async fn resolve_deployed(ctx: &Ctx<'_>, path: &str, is_flow: bool) -> Result<Resolved, String> { let get = if is_flow { diff --git a/backend/windmill-api/src/ai_session_tools/workspace.rs b/backend/windmill-api/src/ai_session_tools/workspace.rs index 3222cc74b3..c576ec087a 100644 --- a/backend/windmill-api/src/ai_session_tools/workspace.rs +++ b/backend/windmill-api/src/ai_session_tools/workspace.rs @@ -1440,14 +1440,21 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult { let prefixes: Vec<Option<String>> = if scope_roots.is_empty() { vec![prefix.filter(|p| !p.is_empty()).map(str::to_string)] } else { - scope_roots.iter().map(|root| Some(format!("{root}/"))).collect() + scope_roots + .iter() + .map(|root| Some(format!("{root}/"))) + .collect() }; let per_page = limit.min(MAX_LIST_LIMIT); let page_number = page.unwrap_or(1).max(1); + let search = opt_str_arg(args, "query") + .map(|q| q.trim().to_lowercase()) + .filter(|q| !q.is_empty()); // Several folders read as one listing, folder after folder, so `limit` stays one cap per // type (per trigger kind for triggers): page N is rows (N-1)*limit..N*limit of each - // concatenation, which takes every folder's first N*limit rows. - let window = (prefixes.len() > 1) + // concatenation, which takes every folder's first N*limit rows. A search pages the same + // way, since the runnables search it goes through pages by cursor, not by page number. + let window = (prefixes.len() > 1 || search.is_some()) .then(|| (page_number - 1) * per_page..page_number * per_page); let mut query = format!("per_page={per_page}"); @@ -1474,6 +1481,10 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult { } } + // Scripts and flows are searched by the server, across the whole workspace rather than + // one fetched page, each word matched in any order; it has already chosen them, so the + // substring filter below leaves them be. + let mut searched = std::collections::HashSet::new(); let mut by_key = Map::new(); // Each type's index into its concatenation across folders, per trigger kind for triggers. let mut index_by_kind: HashMap<String, u64> = HashMap::new(); @@ -1497,6 +1508,40 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult { if let Some(prefix) = prefix { query.push_str(&format!("&path_start={}", enc(prefix))); } + let server_search = search + .as_deref() + .filter(|_| matches!(*item_type, "script" | "flow")); + if let Some(text) = server_search { + let wanted = window.as_ref().map_or(per_page, |w| w.end); + let rows = + search_runnables(ctx, item_type, text, prefix.as_deref(), wanted).await?; + for row in rows { + let index = index_by_kind.entry(format!("{item_type}:")).or_default(); + *index += 1; + if window.as_ref().is_some_and(|w| !w.contains(&(*index - 1))) { + continue; + } + let stored = row.get("path").and_then(Value::as_str).unwrap_or_default(); + let mut item = deployed_item(item_type, None, &row); + // A draft-only row is stored under a generated path: show it the + // way `list_drafts` does, so the draft overlay keys it the same. + let (path, _) = ctx.display_path(item_type, stored); + if let Value::Object(map) = &mut item { + map.insert("path".into(), json!(path)); + put( + map, + "draftPath", + row.get("draft_path") + .filter(|p| p.as_str() != Some(path)) + .cloned(), + ); + } + let key = item_key(item_type, path, None); + searched.insert(key.clone()); + by_key.insert(key, item); + } + continue; + } let route = ctx.ws(&format!( "{}/list?{query}{extra}", service(item_type, trigger_kind)? @@ -1562,21 +1607,21 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult { } } - let query = opt_str_arg(args, "query") - .map(|q| q.trim().to_lowercase()) - .filter(|q| !q.is_empty()); let results: Vec<Value> = by_key .into_iter() - .map(|(_, item)| item) - .chain(access_rows) - .filter(|item| { - let Some(query) = &query else { return true }; + .map(|(key, item)| (searched.contains(&key), item)) + .chain(access_rows.into_iter().map(|item| (false, item))) + .filter(|(searched, item)| { + let Some(query) = search.as_ref().filter(|_| !searched) else { + return true; + }; ["path", "summary"].iter().any(|key| { item.get(*key) .and_then(Value::as_str) .is_some_and(|text| text.to_lowercase().contains(query)) }) }) + .map(|(_, item)| item) .collect(); let listed = pretty(&Value::Array(results)); if scope_roots.is_empty() { @@ -1589,6 +1634,41 @@ async fn list_workspace_items(ctx: &Ctx<'_>, args: &Value) -> ToolResult { )) } +/// The first `wanted` scripts or flows matching `text`, every word in any order, through the +/// runnables search: it pages by cursor and caps a page, so this follows the cursor until it +/// has `wanted` rows or the matches run out. +async fn search_runnables( + ctx: &Ctx<'_>, + item_type: &str, + text: &str, + prefix: Option<&str>, + wanted: u64, +) -> Result<Vec<Value>, String> { + const MAX_RUNNABLES_PAGE: u64 = 1000; + let mut rows = Vec::new(); + let mut cursor: Option<String> = None; + while (rows.len() as u64) < wanted { + let mut route = format!( + "runnables/list?kinds={item_type}&search={}&search_any_order=true&include_draft_only=true&per_page={}", + enc(text), + (wanted - rows.len() as u64).min(MAX_RUNNABLES_PAGE) + ); + if let Some(prefix) = prefix { + route.push_str(&format!("&path_start={}", enc(prefix))); + } + if let Some(cursor) = &cursor { + route.push_str(&format!("&cursor={}", enc(cursor))); + } + let page = ctx.get(&ctx.ws(&route)).await?; + rows.extend(array(page.get("items")).iter().cloned()); + match page["next_cursor"].as_str() { + Some(next) => cursor = Some(next.to_string()), + None => break, + } + } + Ok(rows) +} + /// The card of one workspace item: what `read_workspace_item` returns, under a one-line /// answer, with the item's page and the editor its draft opens in. pub(super) async fn show_item(ctx: &Ctx<'_>, args: &Value) -> ToolResult { diff --git a/backend/windmill-api/src/ai_shared_sessions.rs b/backend/windmill-api/src/ai_shared_sessions.rs index c6554305db..f506640144 100644 --- a/backend/windmill-api/src/ai_shared_sessions.rs +++ b/backend/windmill-api/src/ai_shared_sessions.rs @@ -39,6 +39,8 @@ pub fn workspaced_service() -> Router { post(share_session).layer(DefaultBodyLimit::max(SHARE_BODY_LIMIT)), ) .route("/status", get(get_share_status)) + .route("/list", get(list_shared_sessions)) + .route("/opened/{id}", delete(forget_opened_session)) .route("/set_public/{id}", post(set_public)) .route("/delete/{id}", delete(unshare_session)) } @@ -75,6 +77,8 @@ struct SharedSession { snapshot: Box<RawValue>, /// Whether the caller may stop sharing it: its author, or a workspace admin. can_unshare: bool, + /// Whether the caller is its author. + mine: bool, } #[derive(Serialize)] @@ -83,6 +87,19 @@ struct ShareStatus { share: Option<SharedSessionInfo>, } +#[derive(Serialize)] +struct SharedSessionListItem { + #[serde(flatten)] + info: SharedSessionInfo, + mine: bool, + /// The author's own session id, which means nothing to anyone else: sent to its author only. + #[serde(skip_serializing_if = "Option::is_none")] + session_id: Option<String>, + /// When the caller last opened someone else's share: what dates it in their list. + #[serde(skip_serializing_if = "Option::is_none")] + opened_at: Option<DateTime<Utc>>, +} + #[derive(Deserialize)] struct ShareStatusQuery { session_id: String, @@ -230,6 +247,53 @@ async fn get_share_status( Ok(Json(ShareStatus { share })) } +const LIST_LIMIT: i64 = 500; + +/// The caller's own shares and the ones they opened by link, most recently shared or opened +/// first and without their snapshot. A share nobody sent the caller stays out of their list. +async fn list_shared_sessions( + authed: ApiAuthed, + Extension(db): Extension<DB>, + Path(w_id): Path<String>, +) -> JsonResult<Vec<SharedSessionListItem>> { + require_plain_user_token(&authed)?; + let rows = sqlx::query!( + "SELECT s.id, s.session_id, s.email, s.name, s.is_public, s.message_count, s.created_by, + s.shared_at, o.opened_at AS \"opened_at?\" + FROM ai_shared_session s + LEFT JOIN ai_shared_session_opened o ON o.share_id = s.id AND o.email = $2 + WHERE s.workspace_id = $1 AND (s.email = $2 OR o.share_id IS NOT NULL) + ORDER BY COALESCE(o.opened_at, s.shared_at) DESC + LIMIT $3", + &w_id, + &authed.email, + LIST_LIMIT, + ) + .fetch_all(&db) + .await?; + + Ok(Json( + rows.into_iter() + .map(|row| { + let mine = row.email == authed.email; + SharedSessionListItem { + mine, + session_id: mine.then_some(row.session_id), + opened_at: if mine { None } else { row.opened_at }, + 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, + }, + } + }) + .collect(), + )) +} + /// Only the author changes who can open their link; an admin may only take it down. async fn set_public( authed: ApiAuthed, @@ -311,7 +375,27 @@ async fn get_shared_session( _ => return Err(not_found()), }; + let mine = member.is_some_and(|a| row.email == a.email); + if let Some(reader) = member.filter(|_| !mine) { + // Reading must not depend on the sidebar entry being written. + if let Err(e) = sqlx::query!( + "INSERT INTO ai_shared_session_opened (share_id, email) VALUES ($1, $2) + ON CONFLICT (share_id, email) DO UPDATE SET opened_at = now()", + row.id, + &reader.email, + ) + .execute(&db) + .await + { + tracing::warn!( + "Could not record that {} opened shared session {id}: {e}", + reader.email + ); + } + } + Ok(Json(SharedSession { + mine, 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}")) @@ -327,6 +411,26 @@ async fn get_shared_session( })) } +/// Takes a share out of the caller's list. The share itself stays readable by link. +async fn forget_opened_session( + authed: ApiAuthed, + Extension(db): Extension<DB>, + Path((w_id, id)): Path<(String, Uuid)>, +) -> Result<String> { + require_plain_user_token(&authed)?; + sqlx::query!( + "DELETE FROM ai_shared_session_opened o + USING ai_shared_session s + WHERE o.share_id = s.id AND s.workspace_id = $1 AND o.share_id = $2 AND o.email = $3", + &w_id, + id, + &authed.email, + ) + .execute(&db) + .await?; + Ok("Removed from your shared sessions".to_string()) +} + async fn unshare_session( authed: ApiAuthed, Extension(db): Extension<DB>, diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index bc47259e0d..eeb41244b6 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -68,6 +68,7 @@ use windmill_common::{ jobs::{ normalize_nul_in_args, resolve_delete_after_secs, runnable_ref_to_payload, sanitize_untrusted_args, schedule_job_deletion, JobPayload, JobTriggerKind, RawCode, + RunOrigin, }, runnable_ref::RunnableRef, scripts::ScriptLang, @@ -378,6 +379,23 @@ fn refuse_guest_mode_where_unavailable( ))) } +/// Whether this workspace may deploy apps that stay public (`Anonymous`). On the +/// cloud that takes a paid plan, resolved through the fork/dev root; no workspace +/// admin can lift it, unlike `RestrictAnonymousAppDeployment`. Every deploy that +/// leaves an app public is refused, not only the transition into it, so a free +/// workspace's existing public apps stay frozen until it upgrades. +async fn public_apps_allowed(db: &DB, w_id: &str) -> Result<bool> { + windmill_common::workspaces::paid_features_allowed(db, w_id).await +} + +fn public_app_requires_plan(path: &str) -> Error { + Error::BadRequest(format!( + "app {path} is public (accessible without login), which requires a paid plan on \ + Windmill Cloud. Upgrade this workspace in Workspace Settings > Premium plans to publish \ + or update public apps, or change who can open the app." + )) +} + /// Gate a viewer on the app's `execution_mode`, as far as can be decided without an /// ACL probe. `Ok(true)` means already authorized — anonymous admits anyone, guest /// admits anyone signed in; `Ok(false)` means the caller is a member and still owes @@ -2381,7 +2399,6 @@ fn check_operator_composed_app( referenced.sort(); referenced.dedup(); - refuse_hub_runnables(&referenced)?; Ok(referenced) } @@ -2441,25 +2458,6 @@ fn checked_policy_runnable_paths(policy: &Policy) -> Result<Vec<(AppRunnableKind .collect()) } -fn refuse_hub_runnables(referenced: &[(AppRunnableKind, String)]) -> Result<()> { - for (kind, path) in referenced { - let hub = match kind { - AppRunnableKind::Agent => path.starts_with("hub/"), - AppRunnableKind::Script | AppRunnableKind::Flow => { - RunnableRef::from_path(path, *kind == AppRunnableKind::Flow)? - .path() - .starts_with("hub/") - } - }; - if hub { - return Err(Error::PermissionDenied(format!( - "Operators with builder rights cannot reference the hub runnable {path}. Deploy it to the workspace first." - ))); - } - } - Ok(()) -} - /// Runs on every app write by an operator with builder rights, from inside the create/update /// internals so both raw-app endpoints are covered by one check. /// @@ -2488,7 +2486,22 @@ pub(crate) async fn validate_operator_composed_app( } } let referenced = check_operator_composed_app(write, raw_app, value, policy)?; - require_runnables_readable(authed, db, user_db, w_id, referenced).await + // A Hub path has no workspace row to be readable in: it is held to the rule for naming one. + let mut in_workspace = Vec::with_capacity(referenced.len()); + for (kind, path) in referenced { + if kind != AppRunnableKind::Agent { + let runnable = RunnableRef::from_path(&path, kind == AppRunnableKind::Flow)?; + if runnable.path().starts_with("hub/") { + windmill_api_auth::composed::check_builder_can_name_hub( + &runnable, authed, db, w_id, + ) + .await?; + continue; + } + } + in_workspace.push((kind, path)); + } + require_runnables_readable(authed, db, user_db, w_id, in_workspace).await } fn policy_runs_as_another(policy: &Policy, authed: &ApiAuthed) -> bool { @@ -2853,6 +2866,11 @@ async fn create_app_internal<'a>( "Summary must be less than 300 characters on cloud".to_string(), )); } + if app.policy.execution_mode() == ExecutionMode::Anonymous + && !public_apps_allowed(&db, w_id).await? + { + return Err(public_app_requires_plan(&app.path)); + } } // Resolve the on-behalf-of defaults on the (non-RLS) pool *before* opening // the RLS transaction below: doing these lookups mid-transaction would hold @@ -3878,6 +3896,10 @@ async fn update_app_internal<'a>( } } + // Resolved before the transaction for the reason above; checked against the row + // as written, once every field below has landed. + let public_apps_allowed = public_apps_allowed(&db, w_id).await?; + let mut tx = user_db.clone().begin(&authed).await?; // `app_version.raw_app` is set by whichever endpoint writes the version, so a @@ -4232,6 +4254,19 @@ async fn update_app_internal<'a>( ))); } }; + if !public_apps_allowed + && sqlx::query_scalar!( + "SELECT policy->>'execution_mode' = 'anonymous' FROM app + WHERE path = $1 AND workspace_id = $2", + npath, + w_id + ) + .fetch_one(&mut *tx) + .await? + .unwrap_or(false) + { + return Err(public_app_requires_plan(&npath)); + } // CLI / git-sync deploys ask us to preserve any existing user draft at this // path instead of wiping it as part of the deploy. Only wipe the deployer's // own draft (plus the legacy NULL-email row) — see create_app_internal. @@ -4612,6 +4647,9 @@ async fn execute_component( // tag from the deployed policy and ignore the request body. let is_preview = payload.force_viewer_static_fields.is_some(); let is_inline = payload.raw_code.is_some(); + // Whether the caller, rather than the deployed app, chose `payload.path`: always in preview, + // and in run mode when a Viewer app falls back to a runnable its policy does not declare. + let mut caller_named_path = is_preview; // Preview mode runs request-supplied code as a `Viewer`-mode job (the // app-editor equivalent of `/jobs/run/preview`), so it enforces the same @@ -4632,15 +4670,11 @@ async fn execute_component( })?; // A builder testing the app it is composing only ever previews a deployed runnable // (`path`), confined below to what it may read. Inline `raw_code`, which an `id` also - // requires, is authoring code, so it stays closed to every operator. So is a hub - // path, which `require_path_read_access_for_preview` admits for everyone and - // `runnable_ref_to_payload` then downloads and enqueues: it is exactly the - // unreviewed code the composition check refuses in a flow. - let previews_hub = preview_path.is_some_and(|p| p.starts_with("hub/")); + // requires, is authoring code, so it stays closed to every operator. A hub path, + // which `require_path_read_access_for_preview` admits for everyone, is held further on + // to `check_can_name_runnable`, as it is when a builder saves it as a step. let caps = caller_capabilities(&db, &w_id, authed).await?; - if !caps.code - && (caps.apps == AuthorLevel::None || payload.raw_code.is_some() || previews_hub) - { + if !caps.code && (caps.apps == AuthorLevel::None || payload.raw_code.is_some()) { return Err(Error::PermissionDenied( "Your role cannot run preview jobs in this workspace".to_string(), )); @@ -4879,7 +4913,10 @@ async fn execute_component( triggerables_v2.get(&format!("{}:{p}", payload.component)) }) }) - .or(Some(&policy_triggerables_default)), + .or_else(|| { + caller_named_path = true; + Some(&policy_triggerables_default) + }), _ => None, }) .ok_or_else(|| Error::BadRequest(format!("Path {path} forbidden by policy")))?; @@ -5114,7 +5151,18 @@ async fn execute_component( ) } // flow or script: - (Some(runnable), None, None) => runnable_ref_to_payload(&runnable, &db, &w_id).await?, + (Some(runnable), None, None) => { + let origin = match opt_authed.as_ref() { + Some(viewer) if caller_named_path => RunOrigin::NamedBy(viewer.to_authed_ref()), + None if caller_named_path => { + return Err(Error::NotAuthorized( + "Required to be authed in viewer mode".to_string(), + )) + } + _ => RunOrigin::Deployed, + }; + runnable_ref_to_payload(&runnable, origin, &db, &w_id).await? + } // inline script: "preview" mode, or run mode without an entry in the // `app_script` table (legacy `rawscript/<sha>`-keyed triggerables). (None, Some(raw_code), None) => { @@ -5276,9 +5324,6 @@ async fn execute_component( ), }; let run_query = RunJobQuery { memory_id: Some(memory_id), ..Default::default() }; - if let Some(key) = run_query.memory_key(&w_id, run_path) { - crate::jobs::set_flow_memory_id(&mut tx, uuid, key).await?; - } crate::jobs::file_chat_turn( &mut tx, &owner, @@ -5294,6 +5339,9 @@ async fn execute_component( &args.args, ) .await?; + if let Some(key) = run_query.memory_key(&w_id, run_path) { + crate::jobs::set_flow_memory_id(&mut tx, &w_id, uuid, key).await?; + } } else if let (Some(flow_path), Some(memory_id)) = (flow_path, memory_id) { // A flow keeping no conversation has no row to own its memory, so the key itself is // derived per app and viewer: no viewer can name another's memory. @@ -5305,7 +5353,7 @@ async fn execute_component( flow_path, &format!("app:{path}:{viewer}:{memory_id}"), ); - crate::jobs::set_flow_memory_id(&mut tx, uuid, key).await?; + crate::jobs::set_flow_memory_id(&mut tx, &w_id, uuid, key).await?; } tx.commit().await?; @@ -7173,7 +7221,7 @@ mod embed_token_tests { #[cfg(test)] mod operator_app_tests { use super::{check_operator_composed_app, AppRunnableKind, BuilderAppWrite, Policy}; - use windmill_common::error::{Error, Result}; + use windmill_common::error::Result; use windmill_common::worker::to_raw_value; fn builder_policy(triggerables_v2: serde_json::Value) -> Policy { @@ -7216,22 +7264,24 @@ mod operator_app_tests { vec![(AppRunnableKind::Script, "f/x/s".to_string())] ); - // A hub reference is unreviewed code, refused like it is in a flow. - for key in [ - "a:script/hub/1/x", - "a:script//hub/1/x", - "a:flow//hub/flows/1/x", - // Parses as a workspace flow path, so only the Hub check refuses it. - "a:flow/hub/1/x", + // A hub reference is reported, for the caller to hold to the rule for naming one. + for (key, kind, path) in [ + ("a:script/hub/1/x", AppRunnableKind::Script, "hub/1/x"), + ("a:script//hub/1/x", AppRunnableKind::Script, "/hub/1/x"), + ( + "a:flow//hub/flows/1/x", + AppRunnableKind::Flow, + "/hub/flows/1/x", + ), + ("a:flow/hub/1/x", AppRunnableKind::Flow, "hub/1/x"), ] { let mut policy = builder_policy( serde_json::json!({ key: {"static_inputs": {}, "one_of_inputs": {}} }), ); assert!( - matches!( - composed_app(clean.clone(), &mut policy), - Err(Error::PermissionDenied(_)) - ), + composed_app(clean.clone(), &mut policy) + .unwrap() + .contains(&(kind, path.to_string())), "{key}" ); } @@ -7281,7 +7331,10 @@ mod operator_app_tests { vec![(AppRunnableKind::Agent, "f/x/bot".to_string())] ); let mut policy = builder_policy(serde_json::json!({})); - assert!(composed_app(path_runnable("hub/1/x", "hubscript"), &mut policy).is_err()); + assert_eq!( + composed_app(path_runnable("hub/1/x", "hubscript"), &mut policy).unwrap(), + vec![(AppRunnableKind::Script, "hub/1/x".to_string())] + ); // `execute_component` looks up `<component>:<path>` with an unrestricted component, so a // second colon must not hide the path from validation: `x:y:script/hub/…` resolves at run @@ -7289,7 +7342,9 @@ mod operator_app_tests { let mut policy = builder_policy( serde_json::json!({"x:y:script/hub/123/foo": {"static_inputs": {}, "one_of_inputs": {}}}), ); - assert!(composed_app(clean.clone(), &mut policy).is_err()); + assert!(composed_app(clean.clone(), &mut policy) + .unwrap() + .contains(&(AppRunnableKind::Script, "hub/123/foo".to_string()))); let mut policy = builder_policy( serde_json::json!({"x:y:script/f/x/s": {"static_inputs": {}, "one_of_inputs": {}}}), ); diff --git a/backend/windmill-api/src/apps_raw_bundle.rs b/backend/windmill-api/src/apps_raw_bundle.rs index 61dc4b861d..911d096791 100644 --- a/backend/windmill-api/src/apps_raw_bundle.rs +++ b/backend/windmill-api/src/apps_raw_bundle.rs @@ -23,6 +23,7 @@ use windmill_common::{ error::{Error, Result}, jobs::{JobPayload, RawCode}, scripts::ScriptLang, + utils::strip_json_nul, worker::to_raw_value, DB, }; @@ -134,8 +135,14 @@ pub(crate) async fn bundle_raw_app_sources( let shared_ui = shared_ui_files(user_db, authed, w_id).await?; let mut args: HashMap<String, Box<serde_json::value::RawValue>> = HashMap::new(); - args.insert("files".to_string(), to_raw_value(files)); - args.insert("shared_ui".to_string(), to_raw_value(&shared_ui)); + args.insert( + "files_json".to_string(), + json_text_arg(&serde_json::to_string(files)?), + ); + args.insert( + "shared_ui_json".to_string(), + json_text_arg(&serde_json::to_string(&shared_ui)?), + ); let overridden = std::env::var("WM_RAW_APP_BUNDLER_CLI").is_ok_and(|c| !c.trim().is_empty()); args.insert( "cli_command".to_string(), @@ -145,7 +152,7 @@ pub(crate) async fn bundle_raw_app_sources( "prefer_installed_cli".to_string(), to_raw_value(&!overridden), ); - args.insert("runnables".to_string(), runnables.to_owned()); + args.insert("runnables_json".to_string(), json_text_arg(runnables.get())); let tx = PushIsolationLevel::Isolated(user_db.clone(), authed.clone().into()); let scope_ceiling = windmill_api_auth::caller_scope_ceiling(db, authed).await?; @@ -200,6 +207,18 @@ pub(crate) async fn bundle_raw_app_sources( wait_for_bundle(db, w_id, uuid, authed).await } +/// The app's own data goes to the job as JSON text, for `main` to parse, not as +/// a value: a worker resolves every `$var:`/`$res:` string it finds in a job's +/// args, so a static input holding a reference would reach the policy as the +/// value it resolves to instead of the reference the app states. Text starting +/// with `{` or `"` is left as it is. +/// +/// NULs stripped first, as `push` strips them from args and as the app's value +/// is stored: the policy is keyed by a hash of each inline script. +fn json_text_arg(json: &str) -> Box<serde_json::value::RawValue> { + to_raw_value(&strip_json_nul(json)) +} + /// Waits for the bundle job. The wait itself is bounded by /// `TIMEOUT_WAIT_RESULT`, not by `BUNDLE_TIMEOUT_SECS` — the job's timeout only /// starts once a worker picks it up. @@ -283,3 +302,27 @@ async fn shared_ui_files( .and_then(|f| serde_json::from_value::<HashMap<String, String>>(f).ok()) .unwrap_or_default()) } + +#[cfg(test)] +mod tests { + use super::json_text_arg; + + #[test] + fn app_data_arg_is_text_the_worker_leaves_alone() { + for json in [ + r#"{"a":{"fields":{"p":{"type":"static","value":"$var:u/alice/pw"}}}}"#, + r#"{"/config.txt":"$res:u/alice/db"}"#, + r#""$var:u/alice/pw""#, + ] { + let arg: serde_json::Value = serde_json::from_str(json_text_arg(json).get()).unwrap(); + // One string, so nothing to walk into, and not one a worker resolves. + let text = arg.as_str().unwrap(); + assert_eq!(text, json); + assert!(!text.starts_with('$')); + } + // What the job parses is what the app stores, NUL escapes included. + let arg: serde_json::Value = + serde_json::from_str(json_text_arg(r#"{"a":"x\u0000y"}"#).get()).unwrap(); + assert_eq!(arg.as_str(), Some(r#"{"a":"xy"}"#)); + } +} diff --git a/backend/windmill-api/src/apps_raw_bundler.ts b/backend/windmill-api/src/apps_raw_bundler.ts index 47460be3a6..78bcfdf532 100644 --- a/backend/windmill-api/src/apps_raw_bundler.ts +++ b/backend/windmill-api/src/apps_raw_bundler.ts @@ -17,15 +17,21 @@ declare const __wmillAppPolicy: { } export async function main( - files: Record<string, string>, - shared_ui: Record<string, string> | undefined, + // The app's data comes as JSON text so that the worker leaves the `$var:`/`$res:` + // references in it alone: see `json_text_arg` in `apps_raw_bundle.rs`. + files_json: string, + shared_ui_json: string, cli_command: string[], // Set unless the server was told to build with a specific command. prefer_installed_cli: boolean | undefined, // The app's `value.runnables`, whose policy is derived here for the same // reason the bundle is built here: it has to match what the editor writes. - runnables: Record<string, unknown> | undefined + runnables_json: string ): Promise<{ js_gz: string; css_gz: string; triggerables_v2: Record<string, unknown> }> { + const files: Record<string, string> = JSON.parse(files_json) + const shared_ui: Record<string, string> = JSON.parse(shared_ui_json) + const runnables: Record<string, unknown> | null = JSON.parse(runnables_json) + const fs = await import('node:fs/promises') const path = await import('node:path') diff --git a/backend/windmill-api/src/args.rs b/backend/windmill-api/src/args.rs index 6c1c9824bd..bea546ee0c 100644 --- a/backend/windmill-api/src/args.rs +++ b/backend/windmill-api/src/args.rs @@ -7,14 +7,16 @@ use axum::{ }; use base64::{engine::general_purpose::STANDARD as BASE64_STANDARD, Engine as _}; use bytes::Bytes; -use http::header::CONTENT_TYPE; +use http::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE}; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue; use sqlx::types::JsonRawValue; +use tower_cookies::Cookie; use windmill_common::{ error::Error, jobs::WM_TRACEPARENT, triggers::{RunnableFormat, RunnableFormatVersion, TriggerKind}, + users::COOKIE_NAME, worker::to_raw_value, DB, OTEL_TRACING_ENABLED, }; @@ -67,6 +69,40 @@ pub struct WebhookArgs { pub metadata: WebhookArgsMetadata, } +/// `inline` `Content-Disposition` value naming `filename`, always pure ASCII. +/// +/// Raw non-ASCII bytes in the header are stored as-is by the object store, which +/// then fails to read the attribute back (`HeaderValue::to_str`), turning every +/// download of the object into a 500. A name that is not printable ASCII is +/// therefore sent as RFC 6266 `filename*=UTF-8''<percent-encoded>`, after a +/// `filename="..."` fallback where each such character is replaced by `_`. +#[cfg_attr(not(feature = "parquet"), allow(dead_code))] +pub(crate) fn content_disposition_inline(filename: &str) -> String { + let mut fallback = String::with_capacity(filename.len()); + let mut lossy = false; + for c in filename.chars() { + match c { + '"' | '\\' => { + fallback.push('\\'); + fallback.push(c); + } + ' '..='~' => fallback.push(c), + _ => { + fallback.push('_'); + lossy = true; + } + } + } + if lossy { + format!( + "inline; filename=\"{fallback}\"; filename*=UTF-8''{}", + urlencoding::encode(filename) + ) + } else { + format!("inline; filename=\"{fallback}\"") + } +} + // capture // @@ -171,7 +207,7 @@ impl RawWebhookArgs { ( Attribute::ContentDisposition, if let Some(filename) = filename { - format!("inline; filename=\"{}\"", filename) + content_disposition_inline(&filename) } else { "inline".to_string() }, @@ -363,16 +399,19 @@ impl WebhookArgs { // don't get a stray `_wm_traceparent` arg key. let trace_context = inbound_traceparent(&self.metadata.headers); + // Webhooks are authenticated by Windmill (a webhook capture stands in for one). let headers = build_headers( &self.metadata.headers, self.metadata.query_include_header, runnable_format.has_preprocessor, + true, ); let query = build_query( self.metadata.query.as_deref(), self.metadata.query_include_query, runnable_format.has_preprocessor, + true, ); let mut push_args = match runnable_format { @@ -614,19 +653,50 @@ fn inbound_traceparent(headers: &HeaderMap) -> Option<String> { .map(|s| s.to_string()) } +/// A header's value as a runnable or a capture sees it, `None` to withhold it. +/// +/// Windmill's session cookie is never forwarded: browsers attach it on their own, so it would hand +/// the visitor's session to whoever wrote the runnable. Other cookies are kept. When the request +/// was authenticated by Windmill (`windmill_authed`), its bearer token is withheld as well. +fn forwarded_header_value( + name: &str, + value: &http::HeaderValue, + windmill_authed: bool, +) -> Option<String> { + let value = value.to_str().unwrap_or(""); + if name.eq_ignore_ascii_case(COOKIE.as_str()) { + // Parsed the way `extract_token` reads it, so an encoded name is caught too. + let other_cookies = value + .split(';') + .filter(|c| !Cookie::parse_encoded(*c).is_ok_and(|c| c.name() == COOKIE_NAME)) + .map(str::trim) + .collect::<Vec<_>>(); + return (!other_cookies.is_empty()).then(|| other_cookies.join("; ")); + } + if windmill_authed + && name.eq_ignore_ascii_case(AUTHORIZATION.as_str()) + && value.starts_with("Bearer ") + { + return None; + } + Some(value.to_string()) +} + +/// `windmill_authed`: the caller was authenticated by Windmill, so `Authorization: Bearer` carries +/// their Windmill token. See `forwarded_header_value`. pub fn build_headers( headers: &HeaderMap, include_header: Option<String>, include_all_headers: bool, + windmill_authed: bool, ) -> HashMap<String, Box<RawValue>> { let mut selected_headers = HashMap::new(); if include_all_headers { for (k, v) in headers.iter() { - selected_headers.insert( - k.to_string(), - to_raw_value(&v.to_str().unwrap_or("").to_string()), - ); + if let Some(v) = forwarded_header_value(k.as_str(), v, windmill_authed) { + selected_headers.insert(k.to_string(), to_raw_value(&v)); + } } } else { let whitelist = include_header @@ -636,10 +706,13 @@ pub fn build_headers( .iter() .chain(INCLUDE_HEADERS.iter()) .for_each(|h| { - if let Some(v) = headers.get(h) { + if let Some(v) = headers + .get(h) + .and_then(|v| forwarded_header_value(h, v, windmill_authed)) + { selected_headers.insert( h.to_string().to_lowercase().replace('-', "_"), - to_raw_value(&v.to_str().unwrap_or("").to_string()), + to_raw_value(&v), ); } }); @@ -651,16 +724,20 @@ pub fn build_query( query: Option<&str>, include_query: Option<String>, include_all_query: bool, + windmill_authed: bool, ) -> HashMap<String, Box<RawValue>> { let Some(query) = query else { return HashMap::new(); }; + // `?token=` is a Windmill credential when Windmill authenticated the request. + let withheld = |k: &str| windmill_authed && k == "token"; if include_all_query { let queries = serde_urlencoded::from_str::<HashMap<String, String>>(&query).unwrap_or_default(); queries .into_iter() + .filter(|(k, _)| !withheld(k)) .map(|(k, v)| (k, to_raw_value(&v))) .collect() } else { @@ -671,11 +748,14 @@ pub fn build_query( if !parse_query_args.is_empty() { let queries = serde_urlencoded::from_str::<HashMap<String, String>>(&query).unwrap_or_default(); - parse_query_args.iter().for_each(|h| { - if let Some(v) = queries.get(h) { - args.insert(h.to_string(), to_raw_value(v)); - } - }); + parse_query_args + .iter() + .filter(|h| !withheld(h)) + .for_each(|h| { + if let Some(v) = queries.get(h) { + args.insert(h.to_string(), to_raw_value(v)); + } + }); } args } @@ -755,6 +835,47 @@ mod tests { use super::*; + #[test] + fn test_build_headers_withholds_windmill_credentials() { + let headers = HeaderMap::from_iter([ + (COOKIE, "a=1; token=s; %74oken=s; b=2".parse().unwrap()), + (AUTHORIZATION, "Bearer s".parse().unwrap()), + ]); + let get = + |h: &HashMap<String, Box<RawValue>>, k: &str| h.get(k).map(|v| v.get().to_string()); + + for windmill_authed in [false, true] { + let auth = (!windmill_authed).then(|| r#""Bearer s""#.to_string()); + let all = build_headers(&headers, None, true, windmill_authed); + assert_eq!(get(&all, "cookie").as_deref(), Some(r#""a=1; b=2""#)); + assert_eq!(get(&all, "authorization"), auth); + + let listed = build_headers( + &headers, + Some("cookie,authorization".into()), + false, + windmill_authed, + ); + assert_eq!(get(&listed, "cookie").as_deref(), Some(r#""a=1; b=2""#)); + assert_eq!(get(&listed, "authorization"), auth); + + let query = build_query(Some("token=s&a=1"), None, true, windmill_authed); + assert_eq!(query.contains_key("token"), !windmill_authed); + assert!(query.contains_key("a")); + let listed = build_query( + Some("token=s&a=1"), + Some("token,a".into()), + false, + windmill_authed, + ); + assert_eq!(listed.contains_key("token"), !windmill_authed); + assert!(listed.contains_key("a")); + } + + let only_session = HeaderMap::from_iter([(COOKIE, "token=s".parse().unwrap())]); + assert!(build_headers(&only_session, None, true, false).is_empty()); + } + #[tokio::test] async fn test_bodyless_request_with_json_content_type() { let request = Request::builder() @@ -871,4 +992,34 @@ mod tests { // A name used by both a text and a file part keeps both, in body order. assert_eq!(get("mixed"), r#"["a",{"s3":"k4"}]"#); } + + #[test] + fn test_content_disposition_inline() { + assert_eq!( + content_disposition_inline("report 2024.md"), + r#"inline; filename="report 2024.md""# + ); + assert_eq!( + content_disposition_inline(r#"a"b\c.txt"#), + r#"inline; filename="a\"b\\c.txt""# + ); + assert_eq!( + content_disposition_inline("这是测试.md"), + r#"inline; filename="____.md"; filename*=UTF-8''%E8%BF%99%E6%98%AF%E6%B5%8B%E8%AF%95.md"# + ); + assert_eq!( + content_disposition_inline("a\r\nb\"'*.txt"), + r#"inline; filename="a__b\"'*.txt"; filename*=UTF-8''a%0D%0Ab%22%27%2A.txt"# + ); + for name in ["这是测试.md", "Москва \"x\".pdf", "a\nb", ""] { + let v = content_disposition_inline(name); + assert!( + axum::http::HeaderValue::from_str(&v) + .unwrap() + .to_str() + .is_ok(), + "{v}" + ); + } + } } diff --git a/backend/windmill-api/src/capture.rs b/backend/windmill-api/src/capture.rs index 8e9fb4a823..87d9b41714 100644 --- a/backend/windmill-api/src/capture.rs +++ b/backend/windmill-api/src/capture.rs @@ -569,6 +569,17 @@ async fn set_config( _ => nc, }; + // The listener runs a capture's `$script:`/`$flow:` URL as its saver, as it does a + // trigger's, so the URL takes the trigger save's Hub rule. A capture keeps nothing to compare. + #[cfg(feature = "websocket")] + if matches!(nc.trigger_kind, TriggerKind::Websocket) { + use windmill_api_auth::composed::check_new_hub_paths; + use windmill_trigger::TriggerCrud; + let config = serde_json::to_value(&nc.trigger_config)?; + let new = windmill_trigger_websocket::WebsocketTrigger::config_runnables(&config); + check_new_hub_paths(&new, &[], &authed, &db, &w_id).await?; + } + let mut tx = user_db.begin(&authed).await?; if matches!(nc.trigger_kind, TriggerKind::Postgres) { windmill_common::datatable_roles::lock_datatable_streams(&mut *tx, false).await?; @@ -1250,8 +1261,8 @@ async fn http_payload( .map(|(k, v)| (k.to_string(), v.to_string())) .collect(); - let headers = build_headers(&args.0.metadata.headers, None, true); - let query = build_query(args.0.metadata.query.as_deref(), None, true); + let headers = build_headers(&args.0.metadata.headers, None, true, false); + let query = build_query(args.0.metadata.query.as_deref(), None, true, false); let preprocessor_args = args .clone() diff --git a/backend/windmill-api/src/db.rs b/backend/windmill-api/src/db.rs index 9d311a33bc..56524011fe 100644 --- a/backend/windmill-api/src/db.rs +++ b/backend/windmill-api/src/db.rs @@ -484,7 +484,16 @@ pub async fn wait_for_migrations( "This worker is on Windmill version {GIT_VERSION} (migration version {latest_version}). Only servers run migrations. Waiting for a server with version >= {GIT_VERSION} to apply the migration..." ); - let mut attempts = 0; + // During a rolling upgrade, new workers start at the same time as the new + // server, which needs a while to come up and migrate. Exiting early only + // makes the pod restart and look like a crash loop, so wait long enough to + // cover a normal rollout and only give up if the server is truly not coming. + const RECHECK_SECS: u64 = 3; + // Over 12 rollouts (3,430 worker starts) the longest wait was 94s and + // p99 47s; 3 minutes covers that with margin. + const MAX_WAIT_SECS: u64 = 3 * 60; + const LOG_EVERY: u64 = 10; + let mut attempts: u64 = 0; loop { let is_applied: Result<Option<bool>, sqlx::Error> = @@ -500,16 +509,19 @@ pub async fn wait_for_migrations( ); return Ok(()); } - Ok(_) => { + Ok(_) if attempts % LOG_EVERY == 0 => { tracing::info!( - "Database not up to date yet. This worker (Windmill {GIT_VERSION}, migration version {latest_version}) is waiting for a server with version >= {GIT_VERSION} to run the migration. Rechecking in 3s..." + "Database not up to date yet. This worker (Windmill {GIT_VERSION}, migration version {latest_version}) is waiting for a server with version >= {GIT_VERSION} to run the migration. Waited {}s so far, giving up after {MAX_WAIT_SECS}s...", + attempts * RECHECK_SECS ); } - Err(e) => { + Ok(_) => {} + Err(e) if attempts % LOG_EVERY == 0 => { tracing::info!( - "Could not check migration status (migrations table may not exist yet): {e:#}. Rechecking in 3s..." + "Could not check migration status (migrations table may not exist yet): {e:#}. Rechecking every {RECHECK_SECS}s..." ); } + Err(_) => {} } tokio::select! { @@ -517,13 +529,13 @@ pub async fn wait_for_migrations( tracing::info!("Killpill received, stopping migration wait"); return Ok(()); } - _ = tokio::time::sleep(std::time::Duration::from_secs(3)) => {} + _ = tokio::time::sleep(std::time::Duration::from_secs(RECHECK_SECS)) => {} } attempts += 1; - if attempts >= 10 { + if attempts * RECHECK_SECS >= MAX_WAIT_SECS { tracing::error!( - "Timed out after 10 attempts waiting for migration version {latest_version}. Exiting." + "Timed out after {MAX_WAIT_SECS}s waiting for migration version {latest_version}. Exiting." ); std::process::exit(1); } diff --git a/backend/windmill-api/src/drafts.rs b/backend/windmill-api/src/drafts.rs index 31a7bea2c5..4b0785080d 100644 --- a/backend/windmill-api/src/drafts.rs +++ b/backend/windmill-api/src/drafts.rs @@ -40,13 +40,15 @@ pub fn workspaced_service() -> Router { ) .route("/move/{kind}/{*path}", post(move_draft)) .route("/migrate_legacy/{kind}/{*path}", post(migrate_legacy_draft)) + .route("/transfer", post(transfer_drafts)) } #[derive(Serialize, sqlx::FromRow)] pub struct DraftListItem { pub kind: UserDraftItemKind, pub path: String, - /// Best-effort, read from the draft JSON's `summary` field when present. + /// Best-effort, read from the draft JSON's `summary` field when present, or its + /// `description` for an agent's draft. #[serde(skip_serializing_if = "Option::is_none")] pub summary: Option<String>, /// User-typed friendly path read from the draft JSON's `draft_path` (set by @@ -56,6 +58,10 @@ pub struct DraftListItem { /// home-page list endpoints. #[serde(skip_serializing_if = "Option::is_none")] pub draft_path: Option<String>, + /// A `resource` draft's type: the deployed row's, which a deploy keeps, else the one the + /// draft names. Tells an agent's draft apart without reading each one. + #[serde(skip_serializing_if = "Option::is_none")] + pub resource_type: Option<String>, /// No deployed counterpart exists at this path — the draft is the whole /// item. Kinds without a per-path backing table report `true`. pub draft_only: bool, @@ -249,16 +255,20 @@ fn list_drafts_query(all_users: bool) -> String { d.path, d.typ AS kind, d.created_at, - d.value ->> 'summary' AS summary, + -- An agent's summary is its resource's description. + CASE WHEN rt.resource_type = 'ai_agent' + THEN d.value ->> 'description' + ELSE d.value ->> 'summary' END AS summary, + rt.resource_type, {draft_users} AS draft_users, -- Friendly typed path, by kind (mirrors the home-page list - -- endpoints): scripts bind the Path widget to `script.path`, - -- so it round-trips through the draft JSON's own `path`; + -- endpoints): scripts and agents bind the Path widget to the + -- item's own `path`, so it round-trips through the draft JSON's `path`; -- flows/apps/raw-apps carry a separate `draft_path`. NULLIF -- drops it when empty or equal to the storage path. NULLIF( NULLIF( - CASE WHEN d.typ::text = 'script' + CASE WHEN d.typ::text = 'script' OR rt.resource_type = 'ai_agent' THEN d.value ->> 'path' ELSE d.value ->> 'draft_path' END, ''), @@ -279,6 +289,13 @@ fn list_drafts_query(all_users: bool) -> String { ) END AS unchanged_from_parent FROM draft d + LEFT JOIN LATERAL ( + SELECT COALESCE( + (SELECT r.resource_type FROM resource r + WHERE r.workspace_id = d.workspace_id AND r.path = d.path), + d.value ->> 'resource_type') AS resource_type + WHERE d.typ = 'resource' + ) rt ON true WHERE d.workspace_id = $1{owner_filter} ORDER BY d.path, d.typ, CASE WHEN d.email = $2 THEN 0 WHEN d.email IS NULL THEN 1 ELSE 2 END"# @@ -384,6 +401,105 @@ fn draft_lineage(kind: UserDraftItemKind, value: &str) -> Option<DraftBaseVersio has_base.then_some(base) } +/// A role that composes but does not author in full is held to the composition-only rules on +/// its drafts as on its deploys. `value` is the draft text as stored or about to be. +async fn validate_composed_draft( + authed: &ApiAuthed, + db: &DB, + user_db: &UserDB, + w_id: &str, + kind: UserDraftItemKind, + path: &str, + value: &str, +) -> Result<()> { + let caps = windmill_common::roles::caller_capabilities(db, w_id, authed).await?; + if caps.flows == AuthorLevel::Compose && kind == UserDraftItemKind::Flow { + #[derive(Deserialize)] + struct FlowDraft { + #[serde(default)] + value: FlowValue, + schema: Option<Box<serde_json::value::RawValue>>, + tag: Option<String>, + } + // The text as stored, NULs stripped: a stripped NUL can rename a key into one this + // check reads. + let draft: FlowDraft = serde_json::from_str(&strip_json_nul(value)) + .map_err(|e| Error::BadRequest(format!("Invalid flow draft: {e}")))?; + validate_operator_flow( + &draft.value, + &draft.tag, + draft.schema.as_deref().map(|s| s.get()), + authed, + db, + user_db, + w_id, + ) + .await?; + } + + // An agent draft is held to the rules of its deploy, as a flow draft is: a developer who + // tests it in the agent editor runs its tools as themselves. + if caps.flows != AuthorLevel::Full && kind == UserDraftItemKind::Resource { + #[derive(Deserialize)] + struct ResourceDraft { + #[serde(default)] + args: serde_json::Value, + resource_type: Option<String>, + } + let draft: ResourceDraft = serde_json::from_str(&strip_json_nul(value)) + .map_err(|e| Error::BadRequest(format!("Invalid resource draft: {e}")))?; + // Whatever type the draft names, deploying it over a deployed agent keeps the row's type. + let is_agent = draft.resource_type.as_deref() == Some("ai_agent") + || sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent')", + w_id, + path, + ) + .fetch_one(db) + .await? + .unwrap_or(false); + if is_agent { + let mut tx = user_db.clone().begin(authed).await?; + windmill_api_auth::composed::validate_operator_agent( + &draft.args, + authed, + db, + &mut tx, + w_id, + ) + .await?; + tx.commit().await?; + } + } + + // A raw-app draft carries the app value and its policy side by side. + if caps.apps == AuthorLevel::Compose && kind == UserDraftItemKind::RawApp { + let stripped = strip_json_nul(value); + let draft: serde_json::Value = serde_json::from_str(&stripped) + .map_err(|e| Error::BadRequest(format!("Invalid app draft: {e}")))?; + let mut policy = draft + .get("policy") + .filter(|p| !p.is_null()) + .map(|p| serde_json::from_value::<crate::apps::Policy>(p.clone())) + .transpose() + .map_err(|e| Error::BadRequest(format!("Invalid app draft policy: {e}")))?; + let raw = serde_json::value::RawValue::from_string(stripped.into_owned()) + .map_err(|e| Error::BadRequest(format!("Invalid app draft: {e}")))?; + crate::apps::validate_operator_composed_app( + authed, + db, + user_db, + w_id, + crate::apps::BuilderAppWrite::Draft, + true, + Some(&raw), + policy.as_mut(), + ) + .await?; + } + Ok(()) +} + /// Apply the current user's draft: non-null `value` upserts, `null` (or /// omitted) deletes. Either way, when the existing row is newer than /// `last_sync` (and `force` is false) the op is skipped and the response is @@ -470,95 +586,8 @@ async fn update_draft( } } - // A role that composes but does not author in full is held to the composition-only rules on - // its drafts as on its deploys. - let caps = windmill_common::roles::caller_capabilities(&db, &w_id, &authed).await?; - if caps.flows == AuthorLevel::Compose && kind == UserDraftItemKind::Flow { - if let Some(value) = &req.value { - #[derive(Deserialize)] - struct FlowDraft { - #[serde(default)] - value: FlowValue, - schema: Option<Box<serde_json::value::RawValue>>, - tag: Option<String>, - } - // The text stored below, NULs stripped: a stripped NUL can rename a key into one - // this check reads. - let draft: FlowDraft = serde_json::from_str(&strip_json_nul(value.0.get())) - .map_err(|e| Error::BadRequest(format!("Invalid flow draft: {e}")))?; - validate_operator_flow( - &draft.value, - &draft.tag, - draft.schema.as_deref().map(|s| s.get()), - &authed, - &db, - &user_db, - &w_id, - ) - .await?; - } - } - - // An agent draft is held to the rules of its deploy, as a flow draft is: a developer who - // tests it in the agent editor runs its tools as themselves. - if caps.flows != AuthorLevel::Full && kind == UserDraftItemKind::Resource { - if let Some(value) = &req.value { - #[derive(Deserialize)] - struct ResourceDraft { - #[serde(default)] - args: serde_json::Value, - resource_type: Option<String>, - } - let draft: ResourceDraft = serde_json::from_str(&strip_json_nul(value.0.get())) - .map_err(|e| Error::BadRequest(format!("Invalid resource draft: {e}")))?; - // Whatever type the draft names, deploying it over a deployed agent keeps the row's type. - let is_agent = draft.resource_type.as_deref() == Some("ai_agent") - || sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2 AND resource_type = 'ai_agent')", - &w_id, - path, - ) - .fetch_one(&db) - .await? - .unwrap_or(false); - if is_agent { - let mut tx = user_db.clone().begin(&authed).await?; - windmill_api_auth::composed::validate_operator_agent( - &draft.args, - &authed, - &db, - &mut tx, - &w_id, - ) - .await?; - tx.commit().await?; - } - } - } - - // A raw-app draft carries the app value and its policy side by side. - if caps.apps == AuthorLevel::Compose && kind == UserDraftItemKind::RawApp { - if let Some(value) = &req.value { - let draft: serde_json::Value = serde_json::from_str(&strip_json_nul(value.0.get())) - .map_err(|e| Error::BadRequest(format!("Invalid app draft: {e}")))?; - let mut policy = draft - .get("policy") - .filter(|p| !p.is_null()) - .map(|p| serde_json::from_value::<crate::apps::Policy>(p.clone())) - .transpose() - .map_err(|e| Error::BadRequest(format!("Invalid app draft policy: {e}")))?; - crate::apps::validate_operator_composed_app( - &authed, - &db, - &user_db, - &w_id, - crate::apps::BuilderAppWrite::Draft, - true, - Some(&value.0), - policy.as_mut(), - ) - .await?; - } + if let Some(value) = &req.value { + validate_composed_draft(&authed, &db, &user_db, &w_id, kind, path, value.0.get()).await?; } let applied = if let Some(value) = &req.value { @@ -990,6 +1019,290 @@ async fn move_draft( Ok(format!("moved draft {path} to {new_path}")) } +#[derive(Deserialize, Serialize, Clone)] +pub struct DraftItemRef { + pub kind: UserDraftItemKind, + pub path: String, +} + +#[derive(Deserialize)] +pub struct TransferDraftsRequest { + /// A workspace of this one's family (the same root: its forks, its parent, siblings) to copy + /// the drafts into. Omitted, the call only removes them here (`remove_from_source`). + #[serde(default)] + pub target_workspace: Option<String>, + pub items: Vec<DraftItemRef>, + #[serde(default)] + pub remove_from_source: bool, + /// Overwrite the caller's own drafts of `items` already in the target instead of + /// reporting them as conflicts. For a fork created moments ago, whose only such rows are + /// the fork clone's copies of the very drafts being moved: a save made after the clone + /// must reach the fork before its parent's copy is removed. + #[serde(default)] + pub replace_existing: bool, +} + +#[derive(Serialize)] +pub struct TransferDraftsResponse { + pub copied: Vec<DraftItemRef>, + pub removed: Vec<DraftItemRef>, + /// Items the caller already has a draft of in the target. When non-empty nothing was + /// written: the caller resolves them first rather than have one side silently win. + pub conflicts: Vec<DraftItemRef>, +} + +/// Copy the caller's own drafts of `items` into another workspace of this one's family and/or +/// remove them here, in one transaction, so a session moving to a fork never leaves its work in +/// both places or in neither. +/// +/// Only the caller's rows are touched (never a teammate's or the legacy NULL-email one), so +/// removing needs no write right here, as with discarding one's own draft. Copying needs it +/// in the target. +async fn transfer_drafts( + authed: ApiAuthed, + tokened: crate::auth::Tokened, + Extension(auth_cache): Extension<std::sync::Arc<crate::auth::AuthCache>>, + Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, + Path(w_id): Path<String>, + Json(req): Json<TransferDraftsRequest>, +) -> Result<Json<TransferDraftsResponse>> { + let items: Vec<(UserDraftItemKind, String)> = + req.items.iter().map(|i| (i.kind, i.path.clone())).collect(); + let kinds: Vec<&str> = items.iter().map(|(k, _)| k.as_str()).collect(); + let paths: Vec<&str> = items.iter().map(|(_, p)| p.as_str()).collect(); + let to_refs = |rows: Vec<(UserDraftItemKind, String)>| -> Vec<DraftItemRef> { + rows.into_iter() + .map(|(kind, path)| DraftItemRef { kind, path }) + .collect() + }; + + let mut target_authed = None; + if let Some(target) = req.target_workspace.as_deref() { + // Same root, reached through `parent_workspace_id`. The copy keeps what the target can + // resolve (script lineage it has, members it has) and repairs the rest, so any workspace + // of the family can take the drafts, not only a direct fork. + let same_family = target != w_id + && sqlx::query_scalar!( + r#"WITH RECURSIVE up(id, parent, start, depth) AS ( + SELECT id, parent_workspace_id, id, 0 FROM workspace + WHERE id IN ($1, $2) AND deleted = false + UNION ALL + SELECT w.id, w.parent_workspace_id, up.start, up.depth + 1 + FROM workspace w JOIN up ON w.id = up.parent + WHERE up.depth < 64 + ) + SELECT (SELECT id FROM up WHERE start = $1 AND parent IS NULL) + = (SELECT id FROM up WHERE start = $2 AND parent IS NULL) AS "same""#, + target, + &w_id, + ) + .fetch_one(&db) + .await? + .unwrap_or(false); + if !same_family { + return Err(Error::BadRequest(format!( + "{target} is not in the same workspace family as {w_id}" + ))); + } + // Authentication checked the token against `w_id` only. Re-resolving it against the + // target refuses a token bound to `w_id`, whatever its kind (an external JWT has no + // `token` row), and gives the rights a request to the target would carry: a JWT's + // own claims, not the database's. A job token stays refused even where its claims + // list both workspaces. + let authed_there = auth_cache + .get_authed(Some(target.to_string()), &tokened.token) + .await + .filter(|a| a.job_id.is_none()) + .ok_or_else(|| Error::PermissionDenied(format!("this token cannot act on {target}")))?; + // Secret variable drafts hold values encrypted with the source workspace's key. + if items.iter().any(|(k, _)| *k == UserDraftItemKind::Variable) + && windmill_common::variables::get_workspace_key(&w_id, &db).await? + != windmill_common::variables::get_workspace_key(target, &db).await? + { + return Err(Error::BadRequest(format!( + "{target} has a different encryption key than {w_id}, so variable drafts cannot be copied to it" + ))); + } + let is_member = sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM usr WHERE workspace_id = $1 AND email = $2 AND disabled = false)", + target, + &authed.email, + ) + .fetch_one(&db) + .await? + .unwrap_or(false); + if !is_member && !authed_there.is_admin { + return Err(Error::PermissionDenied(format!("not a member of {target}"))); + } + for (kind, path) in &items { + require_can_write_path(&authed_there, &db, &user_db, target, *kind, path).await?; + } + target_authed = Some(authed_there); + } + + let mut tx = db.begin().await?; + // Holds off a concurrent save of these rows, so the version removed below is the one copied. + // A requested key with no row takes no lock and a draft saved there meanwhile skips the + // checks below, so everything after this works on the locked keys only. + let source_rows = sqlx::query!( + r#"SELECT typ AS "typ: UserDraftItemKind", path, value::text AS "value!" FROM draft + WHERE workspace_id = $1 AND email = $2 + AND (typ::text, path) IN (SELECT * FROM unnest($3::text[], $4::text[])) + FOR UPDATE"#, + &w_id, + &authed.email, + &kinds as &[&str], + &paths as &[&str], + ) + .fetch_all(&mut *tx) + .await?; + let locked: Vec<(UserDraftItemKind, String)> = source_rows + .iter() + .map(|r| (r.typ, r.path.clone())) + .collect(); + let locked_kinds: Vec<&str> = locked.iter().map(|(k, _)| k.as_str()).collect(); + let locked_paths: Vec<&str> = locked.iter().map(|(_, p)| p.as_str()).collect(); + let mut copied = vec![]; + if let (Some(target), Some(target_authed)) = + (req.target_workspace.as_deref(), target_authed.as_ref()) + { + // The copy is a save in the target, so a role that only composes there is held to the + // rules a direct save would apply. Checked on the locked rows, the ones copied. + for row in &source_rows { + validate_composed_draft( + target_authed, + &db, + &user_db, + target, + row.typ, + &row.path, + &row.value, + ) + .await?; + } + // A pipeline node deploys with its `script.hash` as `parent_hash`, refused where that + // version does not exist, and repointing it would deploy over the target's newer one. + let stale_pipelines = sqlx::query_scalar!( + r#"SELECT DISTINCT d.path FROM draft d, + jsonb_array_elements(CASE WHEN jsonb_typeof(d.value::jsonb->'drafts') = 'array' + THEN d.value::jsonb->'drafts' ELSE '[]' END) node + WHERE d.workspace_id = $1 AND d.email = $2 AND d.typ = 'data_pipeline' + AND d.path = ANY($3::text[]) + AND CASE WHEN (node->1->'script'->>'hash' ~ '^[0-9a-f]{16}$') IS NOT TRUE THEN false + ELSE NOT EXISTS (SELECT 1 FROM script sc WHERE sc.workspace_id = $4::text + AND sc.hash = ('x' || (node->1->'script'->>'hash'))::bit(64)::bigint) + END + ORDER BY d.path"#, + &w_id, + &authed.email, + &locked + .iter() + .filter(|(k, _)| *k == UserDraftItemKind::DataPipeline) + .map(|(_, p)| p.clone()) + .collect::<Vec<_>>(), + target, + ) + .fetch_all(&mut *tx) + .await?; + if !stale_pipelines.is_empty() { + return Err(Error::BadRequest(format!( + "{target} lacks a script version these pipeline drafts are based on, so Deploy all would fail there: {}. Deploy them before moving, or pick a workspace that has those versions.", + stale_pipelines.join(", ") + ))); + } + if req.replace_existing { + sqlx::query!( + "DELETE FROM draft + WHERE workspace_id = $1 AND email = $2 + AND (typ::text, path) IN (SELECT * FROM unnest($3::text[], $4::text[]))", + target, + &authed.email, + &locked_kinds as &[&str], + &locked_paths as &[&str], + ) + .execute(&mut *tx) + .await?; + } + let conflicts = sqlx::query!( + r#"SELECT typ AS "typ: UserDraftItemKind", path FROM draft + WHERE workspace_id = $1 AND email = $2 + AND (typ::text, path) IN (SELECT * FROM unnest($3::text[], $4::text[])) + FOR UPDATE"#, + target, + &authed.email, + &locked_kinds as &[&str], + &locked_paths as &[&str], + ) + .fetch_all(&mut *tx) + .await?; + if !conflicts.is_empty() { + return Ok(Json(TransferDraftsResponse { + copied: vec![], + removed: vec![], + conflicts: to_refs(conflicts.into_iter().map(|r| (r.typ, r.path)).collect()), + })); + } + copied = windmill_common::user_drafts::copy_drafts_to_workspace( + &mut *tx, + &w_id, + target, + &authed.email, + Some(&locked), + ) + .await?; + // A save that created one of these rows after the check above was skipped by the copy. + // Returning drops the transaction, so as with any conflict nothing is written. + let raced: Vec<_> = locked + .iter() + .filter(|item| !copied.contains(item)) + .cloned() + .collect(); + if !raced.is_empty() { + return Ok(Json(TransferDraftsResponse { + copied: vec![], + removed: vec![], + conflicts: to_refs(raced), + })); + } + // A copied app policy or trigger may name someone who is not a member of the fork, as a + // fork's own clone may; fork creation re-points those at the user, and so does this. + windmill_api_workspaces::workspaces::repoint_unresolvable_draft_identities( + &mut tx, + target, + target_authed, + Some(&copied), + ) + .await?; + } + + let mut removed = vec![]; + if req.remove_from_source { + removed = sqlx::query!( + r#"DELETE FROM draft + WHERE workspace_id = $1 AND email = $2 + AND (typ::text, path) IN (SELECT * FROM unnest($3::text[], $4::text[])) + RETURNING typ AS "typ: UserDraftItemKind", path"#, + &w_id, + &authed.email, + &locked_kinds as &[&str], + &locked_paths as &[&str], + ) + .fetch_all(&mut *tx) + .await? + .into_iter() + .map(|r| (r.typ, r.path)) + .collect(); + } + tx.commit().await?; + + Ok(Json(TransferDraftsResponse { + copied: to_refs(copied), + removed: to_refs(removed), + conflicts: vec![], + })) +} + #[derive(Deserialize, Debug)] #[serde(rename_all = "snake_case")] pub enum MigrateLegacyDraftAction { diff --git a/backend/windmill-api/src/flow_test.rs b/backend/windmill-api/src/flow_test.rs new file mode 100644 index 0000000000..4f87a6719a --- /dev/null +++ b/backend/windmill-api/src/flow_test.rs @@ -0,0 +1,705 @@ +//! `POST /w/{workspace}/jobs/run/flow_test/{*path}`: run the deployed flow at `path` with some +//! of its steps overridden, for tests. An override either mocks the step's result or replaces +//! its logic with a function of the test's own code. The flow is run as a preview of the edited +//! value, so the SDKs only send step ids, values and function names; everything else is here. + +use std::collections::{HashMap, HashSet}; + +use axum::{ + extract::{Path, Query}, + Extension, Json, +}; +use hyper::StatusCode; +use serde::Deserialize; +use serde_json::{json, value::RawValue, Map, Value}; +use uuid::Uuid; +use windmill_common::{ + db::{UserDB, UserDbWithAuthed}, + error::{Error, Result}, + get_latest_flow_version_info_for_path, + scripts::ScriptLang, + utils::StripPath, +}; +use windmill_types::{ + flows::FlowValue, + jobs::{is_valid_entrypoint_name, ENTRYPOINT_OVERRIDE}, +}; + +use crate::db::{ApiAuthed, DB}; +use crate::jobs::{ + operator_preview_refusal, push_preview_flow_job, require_job_update_read_access, role_can_code, + PreviewFlow, RunJobQuery, +}; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct FlowTestRequest { + #[serde(default)] + args: HashMap<String, Box<RawValue>>, + /// Step id -> `{"return_value": <any>}` or `{"function": "<name>"}`. + #[serde(default)] + steps: HashMap<String, Map<String, Value>>, + /// The job whose code holds the replacement functions, usually the calling test itself. + caller_job_id: Option<Uuid>, +} + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct ReplacementCode { + pub content: String, + pub language: ScriptLang, + pub lock: Option<String>, + pub path: Option<String>, +} + +#[derive(Debug, PartialEq)] +pub(crate) enum StepOverride { + Mock(Value), + Function { entrypoint: String, code: ReplacementCode }, +} + +/// An entrypoint override is only honored by these executors; elsewhere `main` would run. +fn supports_entrypoint_override(language: &ScriptLang) -> bool { + matches!( + language, + ScriptLang::Bun + | ScriptLang::Bunnative + | ScriptLang::Deno + | ScriptLang::Python3 + | ScriptLang::Php + ) +} + +enum ParsedOverride { + Mock(Value), + Function(String), +} + +fn parse_override(step_id: &str, o: Map<String, Value>) -> Result<ParsedOverride> { + let bad = |msg: &str| { + Error::BadRequest(format!( + "step `{step_id}`: {msg}; expected {{\"return_value\": ...}} or {{\"function\": \"<name>\"}}" + )) + }; + if o.len() != 1 { + return Err(bad("an override takes exactly one key")); + } + let (k, v) = o.into_iter().next().unwrap(); + match k.as_str() { + "return_value" => Ok(ParsedOverride::Mock(v)), + "function" => { + let Value::String(name) = v else { + return Err(bad("`function` must be a function name")); + }; + if !is_valid_entrypoint_name(&name) { + return Err(bad(&format!("invalid function name {name:?}"))); + } + Ok(ParsedOverride::Function(name)) + } + _ => Err(bad(&format!("unknown key `{k}`"))), + } +} + +/// The code a job ran: inline for a preview, the deployed script's for a script run. +async fn caller_job_code( + db: &DB, + user_db: &UserDB, + authed: &ApiAuthed, + w_id: &str, + job_id: Uuid, +) -> Result<ReplacementCode> { + require_job_update_read_access(db, user_db, authed, w_id, &job_id, None).await?; + let job = sqlx::query!( + "SELECT kind::text AS \"kind!\", runnable_id, runnable_path, raw_code, raw_lock, + script_lang AS \"script_lang: ScriptLang\", + COALESCE(args ? '_MODULES', false) AS \"has_modules!\" + FROM v2_job WHERE id = $1 AND workspace_id = $2", + job_id, + w_id + ) + .fetch_optional(db) + .await? + .ok_or_else(|| Error::NotFound(format!("Job {job_id} not found")))?; + + // A flow step holds a single file, so a replacement importing a companion file would fail. + let multi_file = || { + Error::BadRequest(format!( + "cannot replace a step with a function of job {job_id}: its script has companion \ + files, which a flow step cannot carry" + )) + }; + if let (Some(content), Some(language)) = (job.raw_code, job.script_lang) { + if job.has_modules { + return Err(multi_file()); + } + return Ok(ReplacementCode { + content, + language, + lock: job.raw_lock, + path: job.runnable_path, + }); + } + match (job.kind.as_str(), job.runnable_id) { + ("script", Some(hash)) => { + // As the caller: reading a run of a script does not grant reading its source. + let mut tx = user_db.clone().begin(authed).await?; + let s = sqlx::query!( + "SELECT content, lock, language AS \"language: ScriptLang\", path, + COALESCE(modules IS NOT NULL AND modules <> '{}'::jsonb, false) + AS \"has_modules!\" + FROM script WHERE hash = $1 AND workspace_id = $2", + hash, + w_id + ) + .fetch_optional(&mut *tx) + .await? + .ok_or_else(|| Error::NotFound(format!("script of job {job_id} not found")))?; + tx.commit().await?; + if s.has_modules { + return Err(multi_file()); + } + Ok(ReplacementCode { + content: s.content, + language: s.language, + lock: s.lock, + path: Some(s.path), + }) + } + (kind, _) => Err(Error::BadRequest(format!( + "cannot replace a step with a function of job {job_id}: its code cannot be read \ + back from a `{kind}` job, only from a script run or a script preview" + ))), + } +} + +#[derive(Clone, Copy, PartialEq)] +enum ModuleKind { + Step, + Preprocessor, + /// An AI agent tool: it has no `mock`, and the agent reads its name and schema from the + /// tool's own definition, so neither kind of override would take effect as written. + Tool, +} + +fn walk_list( + list: Option<&mut Value>, + kind: ModuleKind, + cb: &mut dyn FnMut(ModuleKind, &mut Map<String, Value>), +) { + if let Some(Value::Array(a)) = list { + for m in a { + walk_module(m, kind, cb); + } + } +} + +/// Visits only where the flow schema puts modules: input values and mocks hold arbitrary data, +/// and a module-shaped value there must not be taken for a step. +fn walk_module( + m: &mut Value, + kind: ModuleKind, + cb: &mut dyn FnMut(ModuleKind, &mut Map<String, Value>), +) { + let Value::Object(m) = m else { + return; + }; + cb(kind, m); + let Some(Value::Object(v)) = m.get_mut("value") else { + return; + }; + walk_list(v.get_mut("modules"), ModuleKind::Step, cb); + walk_list(v.get_mut("default"), ModuleKind::Step, cb); + if let Some(Value::Array(branches)) = v.get_mut("branches") { + for b in branches { + walk_list(b.get_mut("modules"), ModuleKind::Step, cb); + } + } + walk_list(v.get_mut("tools"), ModuleKind::Tool, cb); +} + +fn replacement_value( + module: &Map<String, Value>, + entrypoint: &str, + code: &ReplacementCode, +) -> Value { + let mut input_transforms = module + .get("value") + .and_then(|v| v.get("input_transforms")) + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + input_transforms.insert( + ENTRYPOINT_OVERRIDE.to_string(), + json!({ "type": "static", "value": entrypoint }), + ); + let mut raw = json!({ + "type": "rawscript", + "content": code.content, + "language": code.language, + "input_transforms": input_transforms, + }); + if let Some(lock) = &code.lock { + raw["lock"] = json!(lock); + } + if let Some(path) = &code.path { + raw["path"] = json!(path); + } + raw +} + +/// Applies `overrides` to a flow value. Every step id must exist in the flow, so a renamed step +/// fails the test rather than silently running for real. +pub(crate) fn apply_step_overrides( + value: &mut Value, + overrides: &HashMap<String, StepOverride>, +) -> Result<()> { + let mut seen = HashSet::new(); + let mut refused = vec![]; + let mut cb = |kind: ModuleKind, module: &mut Map<String, Value>| { + let Some(id) = module.get("id").and_then(Value::as_str).map(str::to_string) else { + return; + }; + let Some(o) = overrides.get(&id) else { + // An editor pin kept for test runs: a step the test did not override runs for real. + if module + .get("mock") + .and_then(|m| m.get("preview_only")) + .and_then(Value::as_bool) + == Some(true) + { + module.remove("mock"); + } + return; + }; + seen.insert(id.clone()); + match o { + // A preview never runs the preprocessor: `args` are what the flow receives after it. + _ if kind == ModuleKind::Preprocessor => refused.push(format!( + "`{id}` is the flow's preprocessor, which does not run in a flow test: pass the \ + args it would produce instead" + )), + _ if kind == ModuleKind::Tool => refused.push(format!( + "`{id}` is an AI agent tool, which cannot be overridden: override the agent \ + step instead" + )), + StepOverride::Mock(rv) => { + module.insert( + "mock".to_string(), + json!({ "enabled": true, "return_value": rv }), + ); + } + // Called with the flow input in place of its input transforms, so the replacement's + // entrypoint would be ignored and the test's `main` would run. + StepOverride::Function { .. } + if module.get("pass_flow_input_directly") == Some(&Value::Bool(true)) => + { + refused.push(format!( + "`{id}` receives the flow input directly and cannot be replaced with a \ + function: mock its result instead" + )) + } + StepOverride::Function { entrypoint, code } => { + let raw = replacement_value(module, entrypoint, code); + module.insert("value".to_string(), raw); + module.remove("mock"); + } + } + }; + walk_list(value.get_mut("modules"), ModuleKind::Step, &mut cb); + if let Some(m) = value.get_mut("failure_module") { + walk_module(m, ModuleKind::Step, &mut cb); + } + if let Some(m) = value.get_mut("preprocessor_module") { + walk_module(m, ModuleKind::Preprocessor, &mut cb); + } + if !refused.is_empty() { + refused.sort(); + return Err(Error::BadRequest(refused.join("; "))); + } + let mut missing: Vec<&str> = overrides + .keys() + .filter(|k| !seen.contains(*k)) + .map(String::as_str) + .collect(); + if !missing.is_empty() { + missing.sort(); + return Err(Error::BadRequest(format!( + "no step with id {} in the flow", + missing.join(", ") + ))); + } + Ok(()) +} + +/// A cached result is keyed by the flow's own value and args, which leave out the overrides of +/// its subflows, so a test could read the result of a run with other overrides. +fn disable_result_cache(value: &mut Value) { + if let Some(v) = value.as_object_mut() { + v.remove("cache_ttl"); + } + let mut cb = |_: ModuleKind, module: &mut Map<String, Value>| { + module.remove("cache_ttl"); + }; + walk_list(value.get_mut("modules"), ModuleKind::Step, &mut cb); + if let Some(m) = value.get_mut("failure_module") { + walk_module(m, ModuleKind::Step, &mut cb); + } +} + +/// Nesting limit of `a:b:c` step keys, so a subflow calling itself cannot recurse forever. +const MAX_SUBFLOW_DEPTH: usize = 10; + +/// The deployed path of the subflow step `id` of a flow value. +fn subflow_step_path(value: &mut Value, id: &str) -> Result<String> { + let mut found: Option<std::result::Result<String, String>> = None; + let mut cb = |_: ModuleKind, module: &mut Map<String, Value>| { + if module.get("id").and_then(Value::as_str) != Some(id) { + return; + } + let v = module.get("value"); + found = Some( + match ( + v.and_then(|v| v.get("type")).and_then(Value::as_str), + v.and_then(|v| v.get("path")).and_then(Value::as_str), + ) { + (Some("flow"), Some(path)) => Ok(path.to_string()), + _ => Err(format!("`{id}` is not a subflow step")), + }, + ); + }; + walk_list(value.get_mut("modules"), ModuleKind::Step, &mut cb); + if let Some(m) = value.get_mut("failure_module") { + walk_module(m, ModuleKind::Step, &mut cb); + } + match found { + Some(Ok(path)) => Ok(path), + Some(Err(e)) => Err(Error::BadRequest(e)), + None => Err(Error::BadRequest(format!( + "no step with id {id} in the flow" + ))), + } +} + +/// The latest deployed value and tag of a flow, read as the caller. +async fn deployed_flow_value( + db: &DB, + user_db: &UserDB, + authed: &ApiAuthed, + w_id: &str, + path: &str, +) -> Result<(Value, Option<String>)> { + let userdb_authed = UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() }; + let info = + get_latest_flow_version_info_for_path(Some(userdb_authed), db, w_id, path, false).await?; + let stored = sqlx::query_scalar!( + "SELECT value AS \"value: sqlx::types::Json<Value>\" FROM flow_version + WHERE id = $1 AND workspace_id = $2", + info.version, + w_id + ) + .fetch_one(db) + .await?; + Ok((stored.0, info.tag)) +} + +/// Applies `overrides` to `value`. A key `sub:inner` overrides step `inner` of the subflow that +/// step `sub` calls: that subflow's deployed value, overridden in turn, goes to `subflows` under +/// its path, which the run uses for every call of that subflow. +fn resolve_overrides<'a>( + value: &'a mut Value, + overrides: HashMap<String, StepOverride>, + subflows: &'a mut HashMap<String, Value>, + depth: usize, + ctx: (&'a DB, &'a UserDB, &'a ApiAuthed, &'a str), +) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>> { + Box::pin(async move { + let mut local = HashMap::new(); + let mut nested: HashMap<String, HashMap<String, StepOverride>> = HashMap::new(); + for (key, o) in overrides { + match key.split_once(':') { + Some((step, rest)) => { + nested + .entry(step.to_string()) + .or_default() + .insert(rest.to_string(), o); + } + None => { + local.insert(key, o); + } + } + } + if let Some(step) = nested.keys().find(|k| local.contains_key(*k)) { + return Err(Error::BadRequest(format!( + "`{step}` is overridden both as a whole and inside: override one or the other" + ))); + } + apply_step_overrides(value, &local)?; + let mut nested = nested.into_iter().collect::<Vec<_>>(); + nested.sort_by(|a, b| a.0.cmp(&b.0)); + for (step, inner) in nested { + if depth >= MAX_SUBFLOW_DEPTH { + return Err(Error::BadRequest(format!( + "step keys nest at most {MAX_SUBFLOW_DEPTH} subflows deep" + ))); + } + let path = subflow_step_path(value, &step)?; + let (db, user_db, authed, w_id) = ctx; + let (mut sub, _) = deployed_flow_value(db, user_db, authed, w_id, &path).await?; + resolve_overrides(&mut sub, inner, subflows, depth + 1, ctx) + .await + .map_err(|e| match e { + Error::BadRequest(m) => Error::BadRequest(format!("in subflow `{step}`: {m}")), + e => e, + })?; + serde_json::from_value::<FlowValue>(sub.clone()) + .map_err(|e| Error::internal_err(format!("overridden subflow {path}: {e}")))?; + match subflows.get(&path) { + Some(existing) if existing != &sub => { + return Err(Error::BadRequest(format!( + "subflow {path} is overridden differently by two steps calling it: \ + a subflow's overrides apply to every call of it in the run" + ))) + } + _ => { + subflows.insert(path, sub); + } + } + } + Ok(()) + }) +} + +pub(crate) async fn run_flow_test( + authed: ApiAuthed, + Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, + Path((w_id, flow_path)): Path<(String, StripPath)>, + Query(run_query): Query<RunJobQuery>, + Json(req): Json<FlowTestRequest>, +) -> Result<(StatusCode, String)> { + // Even a mock-only test runs an edited flow value; the preview route's builder right is + // not enough for it. + if !role_can_code(&db, &w_id, &authed).await? { + return Err(operator_preview_refusal(None)); + } + let flow_path = flow_path.to_path().to_string(); + + let mut parsed = HashMap::new(); + let mut needs_code = false; + for (id, o) in req.steps { + let p = parse_override(&id, o)?; + needs_code |= matches!(p, ParsedOverride::Function(_)); + parsed.insert(id, p); + } + let code = if needs_code { + let job_id = req.caller_job_id.ok_or_else(|| { + Error::BadRequest( + "replacing a step with a function needs `caller_job_id`, the job whose code \ + defines it" + .to_string(), + ) + })?; + let code = caller_job_code(&db, &user_db, &authed, &w_id, job_id).await?; + if !supports_entrypoint_override(&code.language) { + return Err(Error::BadRequest(format!( + "replacing a step with a function is not supported for {} code", + code.language.as_str() + ))); + } + Some(code) + } else { + None + }; + let overrides = parsed + .into_iter() + .map(|(id, p)| { + let o = match (p, &code) { + (ParsedOverride::Mock(v), _) => StepOverride::Mock(v), + (ParsedOverride::Function(entrypoint), Some(code)) => { + StepOverride::Function { entrypoint, code: code.clone() } + } + (ParsedOverride::Function(_), None) => { + return Err(Error::internal_err("function override without code")) + } + }; + Ok((id, o)) + }) + .collect::<Result<HashMap<_, _>>>()?; + + // Read as the caller, so a flow they cannot see cannot be run through this route. + let (mut value, tag) = deployed_flow_value(&db, &user_db, &authed, &w_id, &flow_path).await?; + let mut subflows = HashMap::new(); + resolve_overrides( + &mut value, + overrides, + &mut subflows, + 0, + (&db, &user_db, &authed, w_id.as_str()), + ) + .await?; + if !subflows.is_empty() { + windmill_common::min_version::MIN_VERSION_SUPPORTS_FLOW_TEST_SUBFLOWS + .assert() + .await?; + } + disable_result_cache(&mut value); + for sub in subflows.values_mut() { + disable_result_cache(sub); + } + let value: FlowValue = serde_json::from_value(value) + .map_err(|e| Error::internal_err(format!("overridden flow value: {e}")))?; + + push_preview_flow_job( + authed, + db, + user_db, + w_id, + run_query, + PreviewFlow { + value, + path: Some(flow_path), + args: Some(req.args), + tag, + restarted_from: None, + temp_script_refs: None, + on_behalf_of: None, + }, + Some(subflows), + ) + .await +} + +#[cfg(test)] +mod tests { + use super::*; + + fn code() -> ReplacementCode { + ReplacementCode { + content: "export function fake(x) { return x }".into(), + language: ScriptLang::Bun, + lock: None, + path: Some("f/tests/t".into()), + } + } + + #[test] + fn overrides_nested_steps_and_keeps_input_transforms() { + let mut v = json!({ "modules": [ + { "id": "a", "value": { "type": "rawscript", "language": "python3", "content": "", + "input_transforms": { "x": { "type": "javascript", "expr": "flow_input.x" } } } }, + { "id": "loop", "value": { "type": "forloopflow", "iterator": { "type": "static", "value": [] }, + "modules": [ { "id": "b", "value": { "type": "identity" }, + "mock": { "enabled": true, "return_value": 0 } } ] } } + ]}); + let overrides = HashMap::from([ + ("a".to_string(), StepOverride::Mock(json!({ "k": 1 }))), + ( + "b".to_string(), + StepOverride::Function { entrypoint: "fake".into(), code: code() }, + ), + ]); + apply_step_overrides(&mut v, &overrides).unwrap(); + + let a = &v["modules"][0]; + assert_eq!( + a["mock"], + json!({ "enabled": true, "return_value": { "k": 1 } }) + ); + assert_eq!(a["value"]["language"], "python3"); + + let b = &v["modules"][1]["value"]["modules"][0]; + assert!( + b.get("mock").is_none(), + "a step's own mock would skip the replacement" + ); + assert_eq!(b["value"]["type"], "rawscript"); + assert_eq!(b["value"]["language"], "bun"); + assert_eq!( + b["value"]["input_transforms"][ENTRYPOINT_OVERRIDE], + json!({ "type": "static", "value": "fake" }) + ); + serde_json::from_value::<FlowValue>(v).unwrap(); + } + + #[test] + fn agent_tool_cannot_be_overridden() { + let v = json!({ "modules": [ { "id": "agent", "value": { "type": "aiagent", + "input_transforms": {}, "tools": [ { "id": "send", "summary": "send", + "value": { "tool_type": "websearch" } } ] } } ] }); + for o in [ + StepOverride::Mock(json!(1)), + StepOverride::Function { entrypoint: "fake".into(), code: code() }, + ] { + let overrides = HashMap::from([("send".to_string(), o)]); + assert!(apply_step_overrides(&mut v.clone(), &overrides).is_err()); + } + } + + #[test] + fn module_shaped_data_is_not_a_step() { + let mut v = json!({ "modules": [ { "id": "a", "value": { "type": "identity" } } ] }); + let fake = json!({ "id": "a", "value": { "type": "identity" } }); + let overrides = HashMap::from([("a".to_string(), StepOverride::Mock(fake.clone()))]); + apply_step_overrides(&mut v, &overrides).unwrap(); + assert_eq!(v["modules"][0]["mock"]["return_value"], fake); + } + + #[test] + fn preprocessor_cannot_be_overridden() { + let mut v = json!({ "modules": [], + "preprocessor_module": { "id": "preprocessor", "value": { "type": "identity" } } }); + let overrides = HashMap::from([("preprocessor".to_string(), StepOverride::Mock(json!(1)))]); + assert!(apply_step_overrides(&mut v, &overrides).is_err()); + } + + #[test] + fn direct_input_step_cannot_be_replaced() { + let mut v = json!({ "modules": [ { "id": "a", "pass_flow_input_directly": true, + "value": { "type": "identity" } } ] }); + let overrides = HashMap::from([( + "a".to_string(), + StepOverride::Function { entrypoint: "fake".into(), code: code() }, + )]); + assert!(apply_step_overrides(&mut v, &overrides).is_err()); + } + + #[test] + fn test_run_pins_are_dropped() { + let mut v = json!({ "modules": [ + { "id": "a", "value": { "type": "identity" }, + "mock": { "enabled": true, "return_value": 1, "preview_only": true } }, + { "id": "b", "value": { "type": "identity" }, + "mock": { "enabled": true, "return_value": 2 } } ] }); + apply_step_overrides(&mut v, &HashMap::new()).unwrap(); + assert!(v["modules"][0].get("mock").is_none()); + assert_eq!(v["modules"][1]["mock"]["return_value"], 2); + } + + #[test] + fn subflow_step_is_found_at_any_depth() { + let mut v = json!({ "modules": [ { "id": "loop", "value": { "type": "forloopflow", + "iterator": { "type": "static", "value": [] }, "modules": [ + { "id": "sub", "value": { "type": "flow", "path": "f/x/sub" } }, + { "id": "s", "value": { "type": "identity" } } ] } } ] }); + assert_eq!(subflow_step_path(&mut v, "sub").unwrap(), "f/x/sub"); + assert!(subflow_step_path(&mut v, "s").is_err()); + assert!(subflow_step_path(&mut v, "nope").is_err()); + } + + #[test] + fn result_cache_is_disabled_at_every_level() { + let mut v = json!({ "cache_ttl": 60, "modules": [ { "id": "loop", "cache_ttl": 60, + "value": { "type": "forloopflow", "iterator": { "type": "static", "value": [] }, + "modules": [ { "id": "s", "cache_ttl": 60, "value": { "type": "identity" } } ] } } ] }); + disable_result_cache(&mut v); + assert!(v.get("cache_ttl").is_none()); + assert!(v["modules"][0].get("cache_ttl").is_none()); + assert!(v["modules"][0]["value"]["modules"][0].get("cache_ttl").is_none()); + } + + #[test] + fn unknown_step_is_an_error() { + let mut v = json!({ "modules": [ { "id": "a", "value": { "type": "identity" } } ] }); + let overrides = HashMap::from([("nope".to_string(), StepOverride::Mock(json!(1)))]); + assert!(apply_step_overrides(&mut v, &overrides).is_err()); + } +} diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index d5d28e9f6b..1a2e8e76bc 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -117,7 +117,8 @@ use windmill_common::{ Suspend, }, jobs::{ - script_path_to_payload, CompletedJob, JobKind, JobPayload, OnBehalfOf, QueuedJob, RawCode, + script_path_to_payload, ChosenBy, CompletedJob, JobKind, JobPayload, OnBehalfOf, QueuedJob, + RawCode, RunOrigin, }, oauth2::HmacSha256, query_builders, @@ -290,6 +291,7 @@ pub fn workspaced_service() -> Router { ) .route("/add_batch_jobs/{n}", post(add_batch_jobs)) .route("/run/preview_flow", post(run_preview_flow_job)) + .route("/run/flow_test/{*path}", post(crate::flow_test::run_flow_test)) .route("/run/agent/{*path}", post(crate::agent_runs::run_agent)) .route( "/run_wait_result/preview_flow", @@ -395,6 +397,10 @@ pub fn workspaced_service() -> Router { "/result_by_id/{job_id}/{node_id}", get(get_result_by_id).layer(cors.clone()), ) + .route( + "/flow/approval_step_detail/{job_id}/{step_id}", + get(get_approval_step_detail), + ) .route( "/job_view_token/{id}", get(get_job_view_token).layer(cors.clone()), @@ -768,32 +774,51 @@ async fn cancel_job_api( async fn cancel_persistent_script_api( OptAuthed(opt_authed): OptAuthed, Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, Path((w_id, script_path)): Path<(String, StripPath)>, Json(CancelJob { reason }): Json<CancelJob>, ) -> error::Result<()> { - let audit_author: AuditAuthor = match opt_authed { - Some(authed) => { - let path = script_path.to_path(); - if !windmill_api_auth::scopes::job_cancel_path_confinement(authed.scopes.as_deref()) - .is_none_or(|c| windmill_api_auth::scopes::cancel_confinement_admits(&c, path)) - { - return Err(Error::NotFound(format!("Script {path} not found"))); - } - (&authed).into() - } - None => { - return Err(Error::BadRequest(format!( - "Cancelling persistent script require to be logged in and member of {w_id}" - ))) - } + let Some(authed) = opt_authed else { + return Err(Error::BadRequest(format!( + "Cancelling persistent script require to be logged in and member of {w_id}" + ))); }; + let path = script_path.to_path(); + if !windmill_api_auth::scopes::job_cancel_path_confinement(authed.scopes.as_deref()) + .is_none_or(|c| windmill_api_auth::scopes::cancel_confinement_admits(&c, path)) + { + return Err(Error::NotFound(format!("Script {path} not found"))); + } + let audit_author: AuditAuthor = (&authed).into(); + let mut first_batch = true; let cancelled_job_ids = windmill_queue::cancel_persistent_script_jobs( &audit_author.username, reason, - script_path.to_path(), + path, &w_id, &db, + // The cancel runs on the root pool, so each run it reaches must pass the per-job check + // `/queue/cancel/{id}` applies. A denial in the first batch refuses the request; one in + // the later batch is a run someone else started after the first committed, so it is left + // running rather than failing a request whose first cancels already landed. + |ids| { + let strict = std::mem::replace(&mut first_batch, false); + let (db, user_db, authed, w_id) = (&db, &user_db, &authed, w_id.as_str()); + async move { + let mut admitted = Vec::with_capacity(ids.len()); + for id in ids { + match require_job_cancel_access(db, user_db, authed, w_id, &id).await { + Ok(()) => admitted.push(id), + // Ended (and restarted) since the batch was read: the next batch has it. + Err(Error::NotFound(_)) => {} + Err(e) if strict => return Err(e), + Err(_) => {} + } + } + Ok(admitted) + } + }, ) .await?; @@ -2326,7 +2351,7 @@ fn job_read_access_cache_key(authed: &ApiAuthed, w_id: &str, job_id: &Uuid) -> [ /// [`require_job_read_access`] for callers (job-update poll / SSE) that haven't /// already loaded `created_by` — fetches it (root DB, by id+workspace) first. -async fn require_job_update_read_access( +pub(crate) async fn require_job_update_read_access( db: &DB, user_db: &UserDB, authed: &ApiAuthed, @@ -4993,6 +5018,8 @@ async fn list_jobs( &w_id, &ListQueueQuery { order_desc: Some(true), ..lq.into() }, qj_fields_ref, + // Uncapped and read in the same statement as the completed half: the runs page + // drops a listed queued job that neither half returns (useJobsLoader's syncer). Pagination { per_page: None, page: None }, true, get_scope_tags(&authed), @@ -5695,6 +5722,325 @@ async fn get_approval_info( })) } +#[derive(Serialize, Debug, PartialEq)] +#[serde(rename_all = "snake_case")] +enum ApprovalStepStatus { + /// The step has not finished running its own script yet. + NotReached, + Skipped, + /// The step failed before asking for approval. + Failed, + Waiting, + Resumed, + /// The run ended while waiting: denied, timed out or cancelled. + NotResumed, +} + +#[derive(Serialize)] +struct StepApproval { + resume_id: u16, + approver: String, + /// Known only while the run is live: a finished run keeps approver names alone. + #[serde(skip_serializing_if = "Option::is_none")] + approved: Option<bool>, + #[serde(skip_serializing_if = "Option::is_none")] + value: Option<serde_json::Value>, + #[serde(skip_serializing_if = "Option::is_none")] + created_at: Option<chrono::DateTime<chrono::Utc>>, +} + +#[derive(Serialize)] +struct ApprovalStepDetail { + flow_id: Uuid, + step_id: String, + status: ApprovalStepStatus, + #[serde(skip_serializing_if = "Option::is_none")] + step_job: Option<Uuid>, + #[serde(skip_serializing_if = "Option::is_none")] + step_summary: Option<String>, + required_events: u32, + #[serde(skip_serializing_if = "Option::is_none")] + timeout: Option<u32>, + #[serde(skip_serializing_if = "Option::is_none")] + suspended_until: Option<chrono::DateTime<chrono::Utc>>, + #[serde(skip_serializing_if = "Option::is_none")] + form_schema: Option<serde_json::Value>, + hide_cancel: bool, + continue_on_disapprove_timeout: bool, + skin: ApprovalSkin, + #[serde(skip_serializing_if = "Option::is_none")] + approval_conditions: Option<ApprovalConditions>, + #[serde(skip_serializing_if = "Option::is_none")] + can_approve: Option<bool>, + #[serde(skip_serializing_if = "Option::is_none")] + description: Option<serde_json::Value>, + #[serde(skip_serializing_if = "Option::is_none")] + default_args: Option<serde_json::Value>, + #[serde(skip_serializing_if = "Option::is_none")] + enums: Option<serde_json::Value>, + approvals: Vec<StepApproval>, + #[serde(skip_serializing_if = "Option::is_none")] + error: Option<serde_json::Value>, +} + +/// Where an approval step stands, from its status module and the one after it: while an +/// approval is pending, the step after holds `WaitingForEvents` with the approval step's job. +fn approval_step_status( + module: Option<&FlowStatusModule>, + next_module: Option<&FlowStatusModule>, + running: bool, + continue_on_disapprove_timeout: bool, + flow_error: Option<&serde_json::Value>, +) -> ApprovalStepStatus { + let canceled = flow_error + .and_then(|e| e.get("name")) + .is_some_and(|n| n == "Canceled"); + match module { + None + | Some(FlowStatusModule::WaitingForPriorSteps { .. }) + // Held by an approval of the step before it. + | Some(FlowStatusModule::WaitingForEvents { .. }) + | Some(FlowStatusModule::WaitingForExecutor { .. }) + | Some(FlowStatusModule::InProgress { .. }) => ApprovalStepStatus::NotReached, + Some(FlowStatusModule::Failure { .. }) => ApprovalStepStatus::Failed, + Some(FlowStatusModule::Success { skipped: true, .. }) => ApprovalStepStatus::Skipped, + Some(FlowStatusModule::Success { job, approvers, .. }) => match next_module { + Some(FlowStatusModule::WaitingForEvents { job: waiting_on, .. }) + if waiting_on == job => + { + if running { + ApprovalStepStatus::Waiting + } else { + ApprovalStepStatus::NotResumed + } + } + // The worker has yet to pick up the step after it and suspend the run. + None | Some(FlowStatusModule::WaitingForPriorSteps { .. }) if running => { + ApprovalStepStatus::Waiting + } + // A denial or timeout that does not continue, or a cancel, fails the step after it + // without running it. The worker records approvers only when it moves on, and a + // step that continues on a timeout moves on with none: its next step can still + // fail unrun, on a branch predicate. + Some(FlowStatusModule::Failure { job: next_job, .. }) + if next_job.is_nil() + && approvers.is_empty() + && (!continue_on_disapprove_timeout || canceled) => + { + ApprovalStepStatus::NotResumed + } + _ => ApprovalStepStatus::Resumed, + }, + } +} + +/// The approval state of one step of a flow run, read in a single query. Only the run's own +/// modules are searched: a step nested in a branch or loop is a module of that branch's or +/// iteration's job, which is the id to pass for it. +async fn get_approval_step_detail( + OptViewToken(view_token): OptViewToken, + authed: ApiAuthed, + Extension(db): Extension<DB>, + Extension(user_db): Extension<UserDB>, + Path((w_id, flow_id, step_id)): Path<(String, Uuid, String)>, +) -> error::Result<Json<ApprovalStepDetail>> { + #[derive(sqlx::FromRow)] + struct Row { + created_by: String, + runnable_path: Option<String>, + permissioned_as_email: String, + running: bool, + module: Option<serde_json::Value>, + next_module: Option<serde_json::Value>, + module_def: Option<serde_json::Value>, + is_last_module: bool, + run_approval_conditions: Option<serde_json::Value>, + suspend_until: Option<chrono::DateTime<chrono::Utc>>, + flow_error: Option<serde_json::Value>, + step_result: Option<serde_json::Value>, + resumes: serde_json::Value, + } + // `v2_job_status` holds the status of a live run only; a finished one's is on + // `v2_job_completed`. Resumes addressed to the run itself + // count toward any of its approval steps, as the worker counts them. + let row = sqlx::query_as::<_, Row>( + "SELECT j.created_by, j.runnable_path, j.permissioned_as_email, + s.id IS NOT NULL AS running, + m.module, m.next_module, + jsonb_path_query_first( + COALESCE(j.raw_flow, fv.value, fn.flow), + '$.modules[*] ? (@.id == $id)', + jsonb_build_object('id', $3::text) + ) AS module_def, + COALESCE( + COALESCE(j.raw_flow, fv.value, fn.flow)->'modules'->-1->>'id' = $3, + false + ) AS is_last_module, + s.flow_status->'approval_conditions' AS run_approval_conditions, + q.suspend_until, + c.result->'error' AS flow_error, + sj.result AS step_result, + COALESCE(( + SELECT jsonb_agg(jsonb_build_object( + 'resume_id', r.resume_id, 'approver', r.approver, + 'approved', r.approved, 'value', r.value, 'created_at', r.created_at + ) ORDER BY r.created_at) + FROM resume_job r + WHERE r.flow = j.id AND (r.job = j.id OR r.job = m.step_job) + ), '[]'::jsonb) AS resumes + FROM v2_job j + LEFT JOIN v2_job_status s ON s.id = j.id + LEFT JOIN v2_job_completed c ON c.id = j.id + LEFT JOIN v2_job_queue q ON q.id = j.id + LEFT JOIN flow_version fv + ON j.raw_flow IS NULL AND j.kind = 'flow' AND fv.id = j.runnable_id + LEFT JOIN flow_node fn + ON j.raw_flow IS NULL AND j.kind = 'flownode' AND fn.id = j.runnable_id + LEFT JOIN LATERAL ( + SELECT e.module, + COALESCE(s.flow_status, c.flow_status)->'modules'->(e.idx::int) AS next_module, + -- A step held by the approval before it carries that approval's job. + CASE WHEN e.module->>'type' <> 'WaitingForEvents' + THEN (e.module->>'job')::uuid END AS step_job + FROM jsonb_array_elements(COALESCE(s.flow_status, c.flow_status)->'modules') + WITH ORDINALITY AS e(module, idx) + WHERE e.module->>'id' = $3 + LIMIT 1 + ) m ON true + LEFT JOIN v2_job_completed sj + ON sj.id = m.step_job AND sj.workspace_id = j.workspace_id + WHERE j.id = $1 AND j.workspace_id = $2", + ) + .bind(&flow_id) + .bind(&w_id) + .bind(&step_id) + .fetch_optional(&db) + .await? + .ok_or_else(|| Error::NotFound(format!("Job {flow_id} not found")))?; + + require_job_read_access( + &db, + &user_db, + &authed, + &w_id, + &flow_id, + &row.created_by, + view_token.as_deref(), + ) + .await?; + + let not_found = || { + Error::NotFound(format!( + "Step {step_id} is not a step of flow run {flow_id}. A step inside a branch or \ + loop belongs to the branch's or iteration's run: pass that run's id instead." + )) + }; + let module_def: FlowModule = row + .module_def + .and_then(|v| serde_json::from_value(v).ok()) + .ok_or_else(not_found)?; + // The worker holds a run only after a step with a positive `required_events` that has a + // step after it (`needs_resume`); the last step's suspend settings never stop the run. + let suspend = module_def + .suspend + .as_ref() + .filter(|s| s.required_events.unwrap_or(0) > 0 && !row.is_last_module) + .ok_or_else(|| { + Error::BadRequest(format!("Step {step_id} is not an approval (suspend) step")) + })?; + let module: Option<FlowStatusModule> = row.module.and_then(|v| serde_json::from_value(v).ok()); + let next_module: Option<FlowStatusModule> = + row.next_module.and_then(|v| serde_json::from_value(v).ok()); + + let step_job = module + .as_ref() + .filter(|m| !matches!(m, FlowStatusModule::WaitingForEvents { .. })) + .and_then(|m| m.job()); + let status = approval_step_status( + module.as_ref(), + next_module.as_ref(), + row.running, + suspend.continue_on_disapprove_timeout.unwrap_or(false), + row.flow_error.as_ref(), + ); + + let live_resumes: Vec<StepApproval> = + serde_json::from_value::<Vec<serde_json::Value>>(row.resumes) + .unwrap_or_default() + .into_iter() + .map(|r| StepApproval { + // Truncated as the worker records it on the finished step, so both agree. + resume_id: r.get("resume_id").and_then(|v| v.as_i64()).unwrap_or(0) as u16, + approver: r + .get("approver") + .and_then(|v| v.as_str()) + .unwrap_or("anonymous") + .to_string(), + approved: r.get("approved").and_then(|v| v.as_bool()), + value: r.get("value").cloned(), + created_at: r + .get("created_at") + .and_then(|v| serde_json::from_value(v.clone()).ok()), + }) + .collect(); + let approvals = if !live_resumes.is_empty() { + live_resumes + } else if let Some(FlowStatusModule::Success { approvers, .. }) = &module { + approvers + .iter() + .map(|a| StepApproval { + resume_id: a.resume_id, + approver: a.approver.clone(), + approved: None, + value: None, + created_at: None, + }) + .collect() + } else { + vec![] + }; + + let waiting = status == ApprovalStepStatus::Waiting; + let approval_conditions = row + .run_approval_conditions + .filter(|_| waiting) + .and_then(|v| serde_json::from_value::<ApprovalConditions>(v).ok()) + .or_else(|| approval_conditions_from_settings(suspend)); + let can_approve = waiting.then(|| { + can_approve_step( + &Some(authed.clone()), + &approval_conditions, + row.runnable_path.as_deref(), + &row.permissioned_as_email, + ) + }); + let step_result_field = |k: &str| row.step_result.as_ref().and_then(|r| r.get(k).cloned()); + + Ok(Json(ApprovalStepDetail { + flow_id, + step_id, + step_job, + step_summary: module_def.summary.clone().filter(|s| !s.trim().is_empty()), + required_events: suspend.required_events.unwrap_or_default(), + timeout: suspend.timeout, + suspended_until: row.suspend_until.filter(|_| waiting), + form_schema: suspend.resume_form.clone(), + hide_cancel: suspend.hide_cancel.unwrap_or(false), + continue_on_disapprove_timeout: suspend.continue_on_disapprove_timeout.unwrap_or(false), + skin: suspend.skin.unwrap_or_default(), + approval_conditions, + can_approve, + description: step_result_field("description"), + default_args: step_result_field("default_args"), + enums: step_result_field("enums"), + approvals, + error: row + .flow_error + .filter(|_| status == ApprovalStepStatus::NotResumed), + status, + })) +} + // --- End new approval system endpoints --- pub async fn resume_suspended_job( @@ -6832,18 +7178,18 @@ pub struct WorkflowTask { } #[derive(Deserialize)] -struct PreviewFlow { - value: FlowValue, - path: Option<String>, - args: Option<HashMap<String, Box<JsonRawValue>>>, - tag: Option<String>, - restarted_from: Option<RestartedFrom>, +pub(crate) struct PreviewFlow { + pub(crate) value: FlowValue, + pub(crate) path: Option<String>, + pub(crate) args: Option<HashMap<String, Box<JsonRawValue>>>, + pub(crate) tag: Option<String>, + pub(crate) restarted_from: Option<RestartedFrom>, /// 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. - temp_script_refs: Option<HashMap<String, String>>, + pub(crate) temp_script_refs: Option<HashMap<String, String>>, /// See `Preview::on_behalf_of`. - on_behalf_of: Option<String>, + pub(crate) on_behalf_of: Option<String>, } #[derive(Debug, Deserialize)] @@ -7138,6 +7484,7 @@ async fn batch_rerun_handle_job( match RunnableRef::from_path(&job.script_path, false) { Ok(script) => push_script_job_by_path_into_queue( authed.clone(), + ChosenBy::Caller, db.clone(), None, user_db.clone(), @@ -7725,6 +8072,7 @@ pub async fn run_script_by_path( let (uuid, _, _) = push_script_job_by_path_into_queue( authed, + ChosenBy::Caller, db, None, user_db, @@ -7940,6 +8288,7 @@ pub async fn run_workflow_as_code( let script = RunnableRef::from_path(job.script_path(), false)?; script_path_to_payload( &script, + RunOrigin::Deployed, Some(userdb_authed), db.clone(), &w_id, @@ -8273,6 +8622,7 @@ pub async fn run_wait_result_job_by_path_get( let (job_payload, tag, delete_after_use, delete_after_secs, timeout, on_behalf_authed) = script_path_to_payload( &script, + RunOrigin::NamedBy(authed.to_authed_ref()), Some(user_db_with_authed), db.clone(), &w_id, @@ -8378,7 +8728,17 @@ pub async fn run_wait_result_flow_by_path_get( ) .await?; - run_wait_result_flow_by_path_internal(db, run_query, &flow, authed, user_db, args, w_id).await + let (result, success) = run_wait_result_flow_by_path_internal( + db.clone(), + run_query, + &flow, + authed, + user_db, + args, + w_id.clone(), + ) + .await?; + result_to_http_response(&db, &w_id, result, success).await } pub async fn run_wait_result_script_by_path( @@ -8406,8 +8766,17 @@ pub async fn run_wait_result_script_by_path( ) .await?; - run_wait_result_script_by_path_internal(db, run_query, &script, authed, user_db, w_id, args) - .await + let (result, success) = run_wait_result_script_by_path_internal( + db.clone(), + run_query, + &script, + authed, + user_db, + w_id.clone(), + args, + ) + .await?; + result_to_http_response(&db, &w_id, result, success).await } pub async fn run_wait_result_script_by_path_internal( @@ -8418,13 +8787,14 @@ pub async fn run_wait_result_script_by_path_internal( user_db: UserDB, w_id: String, args: PushArgsOwned, -) -> error::Result<Response> { +) -> error::Result<(Box<RawValue>, bool)> { check_queue_too_long(&db, QUEUE_LIMIT_WAIT_RESULT.or(run_query.queue_limit)).await?; let db_authed = UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() }; let (job_payload, tag, delete_after_use, delete_after_secs, timeout, on_behalf_of) = script_path_to_payload( script, + RunOrigin::NamedBy(authed.to_authed_ref()), Some(db_authed), db.clone(), &w_id, @@ -8492,7 +8862,8 @@ pub async fn run_wait_result_script_by_path_internal( .await?; tx.commit().await?; - let wait_result = run_wait_result(&db, uuid, &w_id, None, false, &authed.username).await; + let wait_result = + run_wait_result_internal(&db, uuid, &w_id, None, false, &authed.username).await; handle_delete_after_completion(&db, uuid, &w_id, delete_after_use, delete_after_secs).await?; return wait_result; } @@ -8655,7 +9026,17 @@ pub async fn run_wait_result_flow_by_path( ) .await?; - run_wait_result_flow_by_path_internal(db, run_query, &flow, authed, user_db, args, w_id).await + let (result, success) = run_wait_result_flow_by_path_internal( + db.clone(), + run_query, + &flow, + authed, + user_db, + args, + w_id.clone(), + ) + .await?; + result_to_http_response(&db, &w_id, result, success).await } pub async fn stream_flow_by_path( @@ -8790,6 +9171,7 @@ pub async fn stream_job( RunnableId::ScriptId(ScriptId::ScriptPath(script)) | RunnableId::HubScript(script) => { let (uuid, _, _) = push_script_job_by_path_into_queue( authed.clone(), + ChosenBy::Caller, db.clone(), None, user_db, @@ -8898,7 +9280,7 @@ pub async fn run_wait_result_flow_by_path_internal( user_db: UserDB, args: PushArgsOwned, w_id: String, -) -> error::Result<Response> { +) -> error::Result<(Box<RawValue>, bool)> { check_queue_too_long(&db, run_query.queue_limit).await?; let flow_path = flow.path(); @@ -8961,7 +9343,7 @@ pub async fn run_wait_result_flow_by_version_get( let flow_version_info = get_flow_version_info_from_version(&db, version, &w_id, &flow_path).await?; - run_flow_and_wait_result( + let (result, success) = run_flow_and_wait_result( &authed, &db, user_db, @@ -8972,7 +9354,8 @@ pub async fn run_wait_result_flow_by_version_get( args, None, ) - .await + .await?; + result_to_http_response(&db, &w_id, result, success).await } pub async fn run_wait_result_flow_by_version( @@ -9004,7 +9387,7 @@ pub async fn run_wait_result_flow_by_version( let flow_version_info = get_flow_version_info_from_version(&db, version, &w_id, &flow_path).await?; - run_flow_and_wait_result( + let (result, success) = run_flow_and_wait_result( &authed, &db, user_db, @@ -9015,7 +9398,8 @@ pub async fn run_wait_result_flow_by_version( args, None, ) - .await + .await?; + result_to_http_response(&db, &w_id, result, success).await } /// Whether request-supplied SQL from an operator may run. Operators can only run deployed @@ -9082,7 +9466,7 @@ async fn operator_may_run_datatable_query( /// Whether the caller's role may run code of its own: previews, dependency jobs, inline dynamic /// selects, resolving jobs. -async fn role_can_code(db: &DB, w_id: &str, authed: &ApiAuthed) -> error::Result<bool> { +pub(crate) async fn role_can_code(db: &DB, w_id: &str, authed: &ApiAuthed) -> error::Result<bool> { Ok( windmill_common::roles::caller_capabilities(db, w_id, authed) .await? @@ -9092,7 +9476,7 @@ async fn role_can_code(db: &DB, w_id: &str, authed: &ApiAuthed) -> error::Result /// The refusal a member whose role cannot code gets from a preview route. Inside a job the caller /// never ran a preview themselves, so name the one thing the job's token may do. -fn operator_preview_refusal(job_id: Option<Uuid>) -> error::Error { +pub(crate) fn operator_preview_refusal(job_id: Option<Uuid>) -> error::Error { let reason = if job_id.is_some() { "Your role cannot run preview jobs in this workspace: from inside a job, a member \ whose role cannot code may only run a wmill.datatable() query while that job is running" @@ -10006,22 +10390,22 @@ async fn push_flow_dependencies_job( // lock step from becoming the way to run code the write path refuses. if flows_level == AuthorLevel::Compose { validate_operator_composed_flow(&req.flow_value, &None, authed, db, user_db, w_id).await?; - // The job rewrites bookkeeping stored under `req.path` (dependency map, asset usages, - // lock error) even with `skip_flow_update`, so a builder must be able to write there. - crate::drafts::require_can_write_path( - authed, - db, - user_db, - w_id, - windmill_common::user_drafts::UserDraftItemKind::Flow, - &req.path, - ) - .await - .map_err(|e| match e { - error::Error::NotAuthorized(msg) => error::Error::PermissionDenied(msg), - e => e, - })?; } + // The job rewrites bookkeeping stored under `req.path` (dependency map, asset usages, + // lock error) even with `skip_flow_update`, so the caller must be able to write there. + crate::drafts::require_can_write_path( + authed, + db, + user_db, + w_id, + windmill_common::user_drafts::UserDraftItemKind::Flow, + &req.path, + ) + .await + .map_err(|e| match e { + error::Error::NotAuthorized(msg) => error::Error::PermissionDenied(msg), + e => e, + })?; if req.raw_deps.is_some() { return Err(error::Error::MigrationNeeded { @@ -10422,6 +10806,20 @@ async fn run_preview_flow_job( Path(w_id): Path<String>, Query(run_query): Query<RunJobQuery>, Json(raw_flow): Json<PreviewFlow>, +) -> error::Result<(StatusCode, String)> { + push_preview_flow_job(authed, db, user_db, w_id, run_query, raw_flow, None).await +} + +/// `test_subflows`: see `FlowStatus::test_subflows`, written with the job so no worker can +/// start the run without it. +pub(crate) async fn push_preview_flow_job( + authed: ApiAuthed, + db: DB, + user_db: UserDB, + w_id: String, + run_query: RunJobQuery, + raw_flow: PreviewFlow, + test_subflows: Option<HashMap<String, serde_json::Value>>, ) -> error::Result<(StatusCode, String)> { let flows_level = check_operator_can_build(&db, &w_id, &authed, BuilderKind::Flows, "run preview jobs") @@ -10483,6 +10881,7 @@ async fn run_preview_flow_job( 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?; + take_over_memory_turn(&db, &authed, &w_id, &flow_path, &run_query).await?; let (uuid, mut tx) = push( &db, tx, @@ -10526,11 +10925,6 @@ async fn run_preview_flow_job( audit_preview_on_behalf_of(&mut tx, &authed, &w_id, uuid, audited_path, obo).await?; } - // Set memory_id if provided (for agent memory) - if let Some(memory_id) = run_query.memory_key(&w_id, &flow_path) { - set_flow_memory_id(&mut tx, uuid, memory_id).await?; - } - // Handle conversation messages for chat-enabled flows if chat_input_enabled { handle_chat_conversation_messages( @@ -10548,6 +10942,22 @@ async fn run_preview_flow_job( .await?; } + // Set memory_id if provided (for agent memory) + if let Some(memory_id) = run_query.memory_key(&w_id, &flow_path) { + set_flow_memory_id(&mut tx, &w_id, uuid, memory_id).await?; + } + + if let Some(test_subflows) = test_subflows.filter(|m| !m.is_empty()) { + sqlx::query!( + "UPDATE v2_job_status SET flow_status = jsonb_set(flow_status, '{test_subflows}', $2) + WHERE id = $1", + uuid, + sqlx::types::Json(test_subflows) as sqlx::types::Json<HashMap<String, serde_json::Value>> + ) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; Ok((StatusCode::CREATED, uuid.to_string())) @@ -10639,6 +11049,7 @@ async fn run_dynamic_select( let (uuid, _, _) = push_script_job_by_path_into_queue( authed.clone(), + ChosenBy::Caller, db.clone(), None, user_db.clone(), @@ -12224,6 +12635,8 @@ struct CompletedJobResult { success: Option<bool>, completed: bool, result: Option<sqlx::types::Json<Box<RawValue>>>, + #[serde(skip_serializing_if = "Option::is_none")] + is_skipped: Option<bool>, } #[derive(Deserialize)] @@ -12248,7 +12661,8 @@ async fn get_completed_job_result_maybe( "SELECT result AS \"result: sqlx::types::Json<Box<RawValue>>\", result_columns, - status = 'success' AS \"success!\", + status IN ('success', 'skipped') AS \"success!\", + status = 'skipped' AS \"is_skipped!\", created_by AS \"created_by!\" FROM v2_job_completed c JOIN v2_job j USING (id) @@ -12287,6 +12701,7 @@ async fn get_completed_job_result_maybe( success: Some(res.success), completed: true, result: res.result, + is_skipped: Some(res.is_skipped), }) .into_response()) } else if get_started.is_some_and(|x| x) { @@ -12326,6 +12741,7 @@ async fn get_completed_job_result_maybe( completed: false, success: None, result: None, + is_skipped: None, }) .into_response()) } else { @@ -12334,6 +12750,7 @@ async fn get_completed_job_result_maybe( completed: false, success: None, result: None, + is_skipped: None, }) .into_response()) } @@ -12917,6 +13334,54 @@ async fn get_otel_traces( Ok(Json(traces)) } +#[cfg(test)] +mod approval_step_status_tests { + use super::*; + + fn m(v: serde_json::Value) -> FlowStatusModule { + serde_json::from_value(v).unwrap() + } + + #[test] + fn denial_is_not_read_as_resumed() { + let job = "01a1eedb-e408-980c-2af6-e9ac192dc70f"; + let approval = + m(serde_json::json!({"type": "Success", "id": "a", "job": job, "skipped": false})); + let waiting = + m(serde_json::json!({"type": "WaitingForEvents", "id": "b", "job": job, "count": 1})); + let next_failed = m(serde_json::json!({"type": "Failure", "id": "b", "job": Uuid::nil()})); + let next_ran = m( + serde_json::json!({"type": "Success", "id": "b", "job": Uuid::new_v4(), "skipped": false}), + ); + let approved = m(serde_json::json!({"type": "Success", "id": "a", "job": job, + "skipped": false, "approvers": [{"resume_id": 1, "approver": "admin"}]})); + + let status = + |next, running| approval_step_status(Some(&approval), next, running, false, None); + assert_eq!(status(Some(&waiting), true), ApprovalStepStatus::Waiting); + assert_eq!( + status(Some(&waiting), false), + ApprovalStepStatus::NotResumed + ); + // Denied or cancelled while waiting. + assert_eq!( + status(Some(&next_failed), false), + ApprovalStepStatus::NotResumed + ); + assert_eq!(status(Some(&next_ran), false), ApprovalStepStatus::Resumed); + // Approved, then the step after failed before running. + assert_eq!( + approval_step_status(Some(&approved), Some(&next_failed), false, false, None), + ApprovalStepStatus::Resumed + ); + // Timed out and continued, then the step after failed before running. + assert_eq!( + approval_step_status(Some(&approval), Some(&next_failed), false, true, None), + ApprovalStepStatus::Resumed + ); + } +} + #[cfg(test)] mod approval_view_gate_tests { use super::*; @@ -12938,6 +13403,7 @@ mod approval_view_gate_tests { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 0a59323412..a6855a810a 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -124,6 +124,7 @@ mod storage_list_oss; mod workspace_dependencies; mod agent_runs; +mod flow_test; mod ai_evals; mod approvals; #[cfg(all(feature = "enterprise", feature = "private"))] @@ -399,6 +400,7 @@ async fn inject_agent_authed( job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }, job_id: None, }); @@ -489,7 +491,7 @@ pub async fn run_server( .expose_headers([http::header::WWW_AUTHENTICATE]) .allow_origin(Any); - let sp_extension = Arc::new(saml_oss::build_sp_extension().await?); + let sp_extension = Arc::new(saml_oss::build_sp_extension(&db).await?); if server_mode { #[cfg(feature = "embedding")] diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index 0bfa6cd717..c817d314f3 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -15,13 +15,14 @@ use windmill_mcp::common::types::{ }; use windmill_mcp::server::{ BackendResult, CallToolResult, EndpointTool, ErrorData, McpBackend, McpRequest, PathFilter, - SessionAccess, Tool, + RunOutcome, SessionAccess, Tool, }; use crate::auth::AuthCache; use crate::db::ApiAuthed; use crate::jobs::{ - run_wait_result_flow_by_path_internal, run_wait_result_script_by_path_internal, RunJobQuery, + result_to_response, run_wait_result_flow_by_path_internal, + run_wait_result_script_by_path_internal, RunJobQuery, }; use super::auto_generated_endpoints::all_tools; @@ -97,6 +98,15 @@ impl WindmillBackend { } other => other, }; + // A role without `run` reads only, whatever the token grants. The in-app chat applies the + // same rule (`resolveSessionAccess` in `chat/global/sessionAccess.ts`): change both. + let access = if access != SessionAccess::ReadOnly + && !self.can_run(auth, w_id).await.unwrap_or(true) + { + SessionAccess::ReadOnly + } else { + access + }; session::Ctx::new(auth, w_id, &self.base_internal_url, session::access(access)) } @@ -110,6 +120,28 @@ impl WindmillBackend { } } +/// A successful result goes through the same response shaping as the wait-result endpoint, so a +/// `windmill_status_code`/`result` wrapper is unwrapped exactly as it is there. +async fn run_outcome( + workspace_id: &str, + job_id: uuid::Uuid, + (result, success): (Box<serde_json::value::RawValue>, bool), +) -> BackendResult<RunOutcome> { + if success { + let response = result_to_response(result, true, true) + .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; + return Ok(RunOutcome::Success(parse_response_body(response).await?)); + } + Ok(RunOutcome::Failed { + job_id: job_id.to_string(), + run_url: format!( + "{}/run/{job_id}?workspace={workspace_id}", + windmill_common::BASE_URL.load() + ), + result: serde_json::from_str(result.get()).unwrap_or(Value::Null), + }) +} + #[async_trait] impl McpBackend for WindmillBackend { type Auth = ApiAuthed; @@ -124,6 +156,14 @@ impl McpBackend for WindmillBackend { super::external_idp::audit_tool_call(&self.db, auth, workspace_id, tool, refusal).await; } + async fn can_run(&self, auth: &ApiAuthed, workspace_id: &str) -> BackendResult<bool> { + match windmill_common::workspaces::check_role_can_run(&self.db, workspace_id, auth).await { + Ok(()) => Ok(true), + Err(windmill_common::error::Error::PermissionDenied(_)) => Ok(false), + Err(e) => Err(ErrorData::internal_error(e.to_string(), None)), + } + } + async fn list_scripts( &self, auth: &ApiAuthed, @@ -287,7 +327,7 @@ impl McpBackend for WindmillBackend { path: &str, args: Value, request: &McpRequest<'_>, - ) -> BackendResult<Value> { + ) -> BackendResult<RunOutcome> { windmill_common::feature_usage::log_feature_usage("mcp", "runnable_tool_call", "script"); // Called directly rather than through the jobs router, so its run gate does not apply. windmill_common::workspaces::check_role_can_run(&self.db, workspace_id, auth) @@ -299,9 +339,10 @@ impl McpBackend for WindmillBackend { .await .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; + let job_id: uuid::Uuid = ulid::Ulid::new().into(); let result = run_wait_result_script_by_path_internal( self.db.clone(), - RunJobQuery::default(), + RunJobQuery { job_id: Some(job_id), ..Default::default() }, &script, auth.clone(), self.user_db.clone(), @@ -311,7 +352,7 @@ impl McpBackend for WindmillBackend { .await .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; - parse_response_body(result).await + run_outcome(workspace_id, job_id, result).await } async fn run_flow( @@ -321,7 +362,7 @@ impl McpBackend for WindmillBackend { path: &str, args: Value, request: &McpRequest<'_>, - ) -> BackendResult<Value> { + ) -> BackendResult<RunOutcome> { windmill_common::feature_usage::log_feature_usage("mcp", "runnable_tool_call", "flow"); // Called directly rather than through the jobs router, so its run gate does not apply. windmill_common::workspaces::check_role_can_run(&self.db, workspace_id, auth) @@ -333,9 +374,10 @@ impl McpBackend for WindmillBackend { .await .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; + let job_id: uuid::Uuid = ulid::Ulid::new().into(); let result = run_wait_result_flow_by_path_internal( self.db.clone(), - RunJobQuery::default(), + RunJobQuery { job_id: Some(job_id), ..Default::default() }, &flow, auth.clone(), self.user_db.clone(), @@ -345,7 +387,7 @@ impl McpBackend for WindmillBackend { .await .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; - parse_response_body(result).await + run_outcome(workspace_id, job_id, result).await } async fn call_endpoint( diff --git a/backend/windmill-api/src/mcp/utils.rs b/backend/windmill-api/src/mcp/utils.rs index e4245c32aa..1330d7cbca 100644 --- a/backend/windmill-api/src/mcp/utils.rs +++ b/backend/windmill-api/src/mcp/utils.rs @@ -768,16 +768,16 @@ struct McpPreprocessorEvent<'a> { /// Headers withheld from a preprocessor because they authenticate the connection. /// -/// Not a security boundary: a webhook preprocessor receives all three. Withheld -/// because nothing needs them yet, and releasing one later is additive while -/// withdrawing one after runnables read it is not. +/// `build_headers` already withholds Windmill's own credentials. The rest is +/// withheld because nothing needs it yet, and releasing one later is additive +/// while withdrawing one after runnables read it is not. const WITHHELD_FROM_PREPROCESSOR: &[&str] = &["authorization", "cookie", "proxy-authorization"]; /// Every header a preprocessor may see. fn preprocessor_headers( headers: &http::HeaderMap, ) -> HashMap<String, Box<serde_json::value::RawValue>> { - let mut selected = build_headers(headers, None, true); + let mut selected = build_headers(headers, None, true, true); selected.retain(|name, _| { !WITHHELD_FROM_PREPROCESSOR .iter() @@ -1466,6 +1466,7 @@ mod tests { job_id, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/windmill-api/src/oauth2_oss.rs b/backend/windmill-api/src/oauth2_oss.rs index 0513cd5c68..845c989f9a 100644 --- a/backend/windmill-api/src/oauth2_oss.rs +++ b/backend/windmill-api/src/oauth2_oss.rs @@ -18,8 +18,6 @@ use axum::{routing::get, Json, Router}; #[cfg(not(feature = "private"))] use hmac::Mac; -#[cfg(all(feature = "oauth2", not(feature = "private")))] -use itertools::Itertools; #[cfg(not(feature = "private"))] use serde::{Deserialize, Serialize}; #[cfg(all(feature = "oauth2", not(feature = "private")))] @@ -27,8 +25,6 @@ use windmill_common::more_serde::maybe_number_opt; #[cfg(all(feature = "oauth2", not(feature = "private")))] use windmill_oauth::{helpers, AccessToken, RefreshToken, Scope}; -#[cfg(all(feature = "oauth2", not(feature = "private")))] -use crate::OAUTH_CLIENTS; #[cfg(not(feature = "private"))] use windmill_common::error; #[cfg(not(feature = "private"))] @@ -113,22 +109,19 @@ async fn list_logins() -> error::JsonResult<Logins> { return Ok(Json(Logins { oauth: vec![], saml: None, auto_login: None })); } -#[allow(unused)] -#[cfg(all(feature = "oauth2", not(feature = "private")))] -async fn list_connects() -> error::JsonResult<Vec<String>> { - Ok(Json( - (&OAUTH_CLIENTS.load().connects) - .keys() - .map(|x| x.to_owned()) - .collect_vec(), - )) +/// Same shape as the enterprise response, which the connect dialog reads. +#[cfg(not(feature = "private"))] +#[derive(Serialize)] +struct OAuthConnectListItem { + name: String, + supports_client_credentials: bool, + has_shared_credentials: bool, } -#[allow(unused)] -#[cfg(not(all(feature = "oauth2", not(feature = "private"))))] -async fn list_connects() -> windmill_common::error::JsonResult<Vec<String>> { +#[cfg(not(feature = "private"))] +async fn list_connects() -> error::JsonResult<Vec<OAuthConnectListItem>> { // Implementation is not open source - return Ok(axum::Json(vec![])); + Ok(Json(vec![])) } #[cfg(not(feature = "private"))] diff --git a/backend/windmill-api/src/offboarding.rs b/backend/windmill-api/src/offboarding.rs index 7c8b2d4d8a..8dc53a7c72 100644 --- a/backend/windmill-api/src/offboarding.rs +++ b/backend/windmill-api/src/offboarding.rs @@ -130,15 +130,9 @@ struct WorkspaceReassignment { // ---- Preview helpers ---- -/// The principal a departing member's runnables run as, or `None` when none of them are theirs -/// to hand over. `usr.username` is constrained to `[\w-]+`, so a member is `u/{username}`, except -/// a legacy `group-*` username, which canonicalizes to the group it names: what runs under that -/// principal runs as the group, which outlives the member. `None` binds NULL, which the -/// `on_behalf_of = $n` queries then match nowhere. +/// `None` binds NULL, which the `on_behalf_of = $n` queries then match nowhere. fn departing_principal(username: &str) -> Option<String> { - use windmill_common::users::{username_to_permissioned_as, PERMISSIONED_AS_GROUP_PREFIX}; - let principal = username_to_permissioned_as(username); - (!principal.starts_with(PERMISSIONED_AS_GROUP_PREFIX)).then_some(principal) + windmill_common::users::username_to_own_permissioned_as(username) } async fn get_offboard_preview( @@ -206,19 +200,7 @@ async fn get_offboard_preview( .fetch_all(db) .await?; - let trigger_tables = [ - "http_trigger", - "websocket_trigger", - "kafka_trigger", - "postgres_trigger", - "mqtt_trigger", - "amqp_trigger", - "nats_trigger", - "sqs_trigger", - "gcp_trigger", - "azure_trigger", - "email_trigger", - ]; + let trigger_tables = crate::users::TRIGGER_TABLES; let mut triggers = HashMap::new(); for table in &trigger_tables { // SAFETY: `table` comes from a hardcoded allowlist `trigger_tables`, not user input. @@ -1153,19 +1135,7 @@ async fn offboard_user_from_workspace<'c>( ).execute(&mut **tx).await?; // ---- triggers (all 10 types with path/permissioned_as) ---- - let trigger_tables = [ - "http_trigger", - "websocket_trigger", - "kafka_trigger", - "postgres_trigger", - "mqtt_trigger", - "amqp_trigger", - "nats_trigger", - "sqs_trigger", - "gcp_trigger", - "azure_trigger", - "email_trigger", - ]; + let trigger_tables = crate::users::TRIGGER_TABLES; let mut triggers_reassigned: i64 = 0; // SAFETY: `table` comes from a hardcoded allowlist `trigger_tables`, not user input. @@ -1208,6 +1178,14 @@ async fn offboard_user_from_workspace<'c>( .await?; } + crate::users::move_handler_paths( + tx, + w_id, + &format!("u/{username}/"), + &format!("{new_prefix}/"), + ) + .await?; + // NOTE: extra_perms cleanup, folder owners, favorites, inputs, captures, // and token deletion are handled by delete_workspace_user_internal when delete_user=true. // They are NOT done here for reassign-only (delete_user=false) since the user stays. diff --git a/backend/windmill-api/src/public_app_layer.rs b/backend/windmill-api/src/public_app_layer.rs index 8a55e61289..dad4a761d3 100644 --- a/backend/windmill-api/src/public_app_layer.rs +++ b/backend/windmill-api/src/public_app_layer.rs @@ -79,6 +79,7 @@ fn is_public_route_whitelisted(path: &str) -> bool { "/a/*", "/api/oauth/get_connect/*", "/Inter-Variable.woff2", + "/Inter-Variable-Italic.woff2", ]; for pattern in &whitelist { @@ -178,6 +179,7 @@ mod tests { assert!(is_public_route_whitelisted( "/api/w/workspace/resources/list" )); + assert!(is_public_route_whitelisted("/Inter-Variable-Italic.woff2")); // Non-whitelisted routes assert!(!is_public_route_whitelisted("/api/version")); diff --git a/backend/windmill-api/src/runnables.rs b/backend/windmill-api/src/runnables.rs index 0037a37042..ebd5b9b603 100644 --- a/backend/windmill-api/src/runnables.rs +++ b/backend/windmill-api/src/runnables.rs @@ -60,6 +60,8 @@ struct ListRunnablesQuery { include_without_main: Option<bool>, /// Restrict to paths under this prefix (owner/folder filter). path_start: Option<String>, + /// Comma-separated exact paths: list only the rows at one of them. + paths: Option<String>, /// Comma-separated labels; a row matches if it (or its folder) carries all. label: Option<String>, /// Case-insensitive fuzzy match on `summary (path)`, mirroring how the homepage @@ -69,6 +71,9 @@ struct ListRunnablesQuery { /// that holds no ASCII-alphanumeric character at all — `" "`, `"_"`, `"привет"` — /// yields no terms and matches nothing, as it does on the homepage. search: Option<String>, + /// Match each `search` term anywhere, in any order, rather than in the order given: + /// what a caller guessing at words wants, where the homepage ranks a typed prefix. + search_any_order: Option<bool>, per_page: Option<usize>, /// Opaque keyset cursor from a previous page's `next_cursor`. cursor: Option<String>, @@ -199,6 +204,17 @@ fn search_terms(search: &str) -> Vec<&str> { .collect() } +/// The terms of a `search_any_order` query: words in any script, since a caller guessing at +/// words may write them in the language the summaries are in. The ordered search keeps the +/// homepage's ASCII rule, which drops what its matcher drops. +fn any_order_terms(search: &str) -> Vec<&str> { + search + .split(|c: char| !(c.is_alphanumeric() || c == '\'')) + .filter(|t| !t.is_empty()) + .take(MAX_SEARCH_TERMS) + .collect() +} + /// The string a search matches against: `summary (path)`, or the bare path when /// there is no summary — what the homepage concatenates before ranking, so both /// halves are searchable as one and a query may span them. @@ -519,13 +535,33 @@ async fn list_runnables( // `u/<caller>/draft_<uuid>` it is parked at. draft_common.push(format!("COALESCE(o.draft_path, o.path) LIKE {}", p)); } + if let Some(ps) = q.paths.as_ref().filter(|s| !s.is_empty()) { + let p = add_bind(&mut binds, ps.clone()); + common.push(format!("o.path = ANY(string_to_array({p}, ','))")); + draft_common.push(format!( + "COALESCE(o.draft_path, o.path) = ANY(string_to_array({p}, ','))" + )); + } if let Some(search) = q.search.as_ref().filter(|s| !s.is_empty()) { - let terms = search_terms(search); + let terms = if q.search_any_order == Some(true) { + any_order_terms(search) + } else { + search_terms(search) + }; if terms.is_empty() { // A search of nothing but separators is still a search: it must match nothing, // where no predicate at all would answer it with the whole workspace. common.push("false".to_string()); draft_common.push("false".to_string()); + } else if q.search_any_order == Some(true) { + for term in terms { + let p = add_bind(&mut binds, format!("%{}%", escape_like(term))); + common.push(format!("{} ILIKE {p}", searchable_name("o.path"))); + draft_common.push(format!( + "{} ILIKE {p}", + searchable_name("COALESCE(o.draft_path, o.path)") + )); + } } else { // `%` between the terms is what makes them a fuzzy match rather than a literal // one: each must appear whole, in this order, with anything in between. The diff --git a/backend/windmill-api/src/saml_oss.rs b/backend/windmill-api/src/saml_oss.rs index 2747f9ef96..c8e9071624 100644 --- a/backend/windmill-api/src/saml_oss.rs +++ b/backend/windmill-api/src/saml_oss.rs @@ -18,7 +18,7 @@ use axum::{routing::post, Router}; pub struct ServiceProviderExt(); #[cfg(not(feature = "private"))] -pub async fn build_sp_extension() -> anyhow::Result<ServiceProviderExt> { +pub async fn build_sp_extension(_db: &crate::db::DB) -> anyhow::Result<ServiceProviderExt> { return Ok(ServiceProviderExt()); } diff --git a/backend/windmill-api/src/slack_agents.rs b/backend/windmill-api/src/slack_agents.rs index 7505ad48e9..a2a07ef92f 100644 --- a/backend/windmill-api/src/slack_agents.rs +++ b/backend/windmill-api/src/slack_agents.rs @@ -1135,7 +1135,7 @@ async fn wait_for_result( while std::time::Instant::now() < deadline { let row = sqlx::query!( "SELECT result AS \"result: sqlx::types::Json<serde_json::Value>\", - status = 'success' AS \"success!\" + status IN ('success', 'skipped') AS \"success!\" FROM v2_job_completed WHERE id = $1 AND workspace_id = $2", job_id, w_id diff --git a/backend/windmill-api/src/static_assets.rs b/backend/windmill-api/src/static_assets.rs index e469e91249..8594fc62e7 100644 --- a/backend/windmill-api/src/static_assets.rs +++ b/backend/windmill-api/src/static_assets.rs @@ -18,6 +18,8 @@ use hyper::Uri; use mime_guess::mime; #[cfg(feature = "static_frontend")] use rust_embed::RustEmbed; +#[cfg(feature = "static_frontend")] +use windmill_common::worker::CLOUD_HOSTED; // Content Security Policy configuration #[cfg(feature = "static_frontend")] @@ -71,6 +73,22 @@ fn query_has_flag(query: Option<&str>, flag: &str) -> bool { query.is_some_and(|q| q.split('&').any(|kv| kv.split('=').next() == Some(flag))) } +/// Paths served with `X-Robots-Tag: noindex, nofollow`. The app is client-rendered, +/// so a meta tag only exists after a render pass; the header is seen on the first +/// fetch. +/// +/// Login and its siblings carry a different `rd` on every page that links to them, +/// so a crawler meets thousands of URLs for one form. On cloud, public apps +/// (`/public/` and custom paths `/a/`) are published by anyone with a paid +/// workspace; spam apps get linked from outside and indexed under our domain. A +/// self-hoster may want a public app indexed, so that rule is cloud-only. +#[cfg(feature = "static_frontend")] +fn needs_noindex(original_path: &str, cloud_hosted: bool) -> bool { + original_path.starts_with("/user/") + || (cloud_hosted + && (original_path.starts_with("/public/") || original_path.starts_with("/a/"))) +} + fn serve_path(path: &str, original_path: &str, query: Option<&str>) -> Response<Body> { if path.starts_with("api/") { return Response::builder().status(404).body(Body::empty()).unwrap(); @@ -92,11 +110,7 @@ fn serve_path(path: &str, original_path: &str, query: Option<&str>) -> Response< .header("Cross-Origin-Resource-Policy", "cross-origin"); } - // Login and its siblings carry a different `rd` on every page that links - // to them, so a crawler meets thousands of URLs for one form. The app is - // client-rendered, so a meta tag only exists after a render pass; the - // header is seen on the first fetch. - if original_path.starts_with("/user/") { + if needs_noindex(original_path, *CLOUD_HOSTED) { res = res.header("X-Robots-Tag", "noindex, nofollow"); } @@ -211,4 +225,30 @@ mod tests { )); assert!(!needs_cross_origin_isolation("/", None)); } + + #[test] + fn test_needs_noindex() { + // login and its siblings are noindex on every instance + for cloud in [false, true] { + assert!(needs_noindex("/user/login", cloud)); + assert!(needs_noindex("/user/logout", cloud)); + } + + // public apps and custom paths are noindex on cloud only + assert!(needs_noindex("/public/ws/secret", true)); + assert!(needs_noindex("/a/my/path", true)); + assert!(!needs_noindex("/public/ws/secret", false)); + assert!(!needs_noindex("/a/my/path", false)); + + // other pages are never noindex + for cloud in [false, true] { + assert!(!needs_noindex("/scripts/get/u/foo/bar", cloud)); + assert!(!needs_noindex("/apps/get/u/foo/bar", cloud)); + assert!(!needs_noindex("/", cloud)); + // `/api/` must not be caught by the `/a/` prefix + assert!(!needs_noindex("/api/version", cloud)); + // nor `/users...` by `/user/` + assert!(!needs_noindex("/users", cloud)); + } + } } diff --git a/backend/windmill-api/src/triggers/http/handler.rs b/backend/windmill-api/src/triggers/http/handler.rs index daff81249f..402cc28696 100644 --- a/backend/windmill-api/src/triggers/http/handler.rs +++ b/backend/windmill-api/src/triggers/http/handler.rs @@ -26,7 +26,7 @@ use windmill_common::{ db::UserDB, error::{Error, Result}, global_settings::HTTP_ROUTE_DEFAULT_ALLOWED_ORIGINS, - jobs::JobTriggerKind, + jobs::{ChosenBy, JobTriggerKind}, runnable_ref::RunnableRef, triggers::{TriggerKind, TriggerMetadata}, utils::{not_found_if_none, StripPath}, @@ -708,7 +708,7 @@ async fn route_job( .unwrap_or("inline".parse().unwrap()) }, |filename| { - format!("inline; filename=\"{}\"", filename) + crate::args::content_disposition_inline(filename) .parse() .unwrap_or("inline".parse().unwrap()) }, @@ -759,6 +759,10 @@ async fn route_job( ¶ms, runnable_format, trigger.wrap_body, + matches!( + trigger.authentication_method, + AuthenticationMethod::Windmill + ), ) .map(windmill_queue::PushArgsOwned::omit_untrusted_interpolation) .map_err(|e| e.into_response())?; @@ -769,6 +773,7 @@ async fn route_job( &db, Some(user_db), authed, + ChosenBy::Deployed, &trigger.workspace_id, &runnable, args, @@ -802,6 +807,7 @@ async fn route_job( None, Some(user_db.clone()), authed.clone(), + ChosenBy::Deployed, &trigger.workspace_id, &runnable, args, @@ -864,6 +870,7 @@ async fn route_job( &db, Some(user_db), authed, + ChosenBy::Deployed, &trigger.workspace_id, &runnable, args, @@ -881,6 +888,7 @@ async fn route_job( &db, Some(user_db), authed, + ChosenBy::Deployed, &trigger.workspace_id, &runnable, args, diff --git a/backend/windmill-api/src/triggers/http/http_trigger_args.rs b/backend/windmill-api/src/triggers/http/http_trigger_args.rs index f8460f42e2..2dacbdb50d 100644 --- a/backend/windmill-api/src/triggers/http/http_trigger_args.rs +++ b/backend/windmill-api/src/triggers/http/http_trigger_args.rs @@ -121,9 +121,15 @@ impl HttpTriggerArgs { params: &HashMap<String, String>, format: RunnableFormat, wrap_body: bool, + windmill_authed: bool, ) -> Result<PushArgsOwned, Error> { - let headers = build_headers(&self.0.metadata.headers, None, true); - let query = build_query(self.0.metadata.query.as_deref(), None, true); + let headers = build_headers(&self.0.metadata.headers, None, true, windmill_authed); + let query = build_query( + self.0.metadata.query.as_deref(), + None, + true, + windmill_authed, + ); match format { RunnableFormat { has_preprocessor: true, version: RunnableFormatVersion::V2 } => { // we don't care about wrap_body in v2 diff --git a/backend/windmill-api/src/users.rs b/backend/windmill-api/src/users.rs index 5f546a7bed..6966bfd539 100644 --- a/backend/windmill-api/src/users.rs +++ b/backend/windmill-api/src/users.rs @@ -284,11 +284,14 @@ async fn rename_user( validate_username(&ru.new_username)?; - let old_instance_username = - sqlx::query_scalar!("SELECT username FROM password WHERE email = $1", user_email) - .fetch_optional(&mut *tx) - .await? - .flatten(); + let old_instance_account = sqlx::query!( + "SELECT username, super_admin FROM password WHERE email = $1", + user_email + ) + .fetch_optional(&mut *tx) + .await?; + let is_super_admin = old_instance_account.as_ref().is_some_and(|a| a.super_admin); + let old_instance_username = old_instance_account.and_then(|a| a.username); sqlx::query!( "UPDATE password SET username = $1 WHERE email = $2", @@ -302,8 +305,13 @@ async fn rename_user( // outside their workspaces has none, yet an app can name them: their principal is // `u/{password.username}`, which this rename just moved. Matching on the address as well // keeps a like-named member of some other workspace out of it. - if let Some(old_username) = old_instance_username.filter(|u| *u != ru.new_username) { - let old_principal = windmill_common::users::username_to_permissioned_as(&old_username); + if let Some((old_username, old_principal)) = old_instance_username + .filter(|u| *u != ru.new_username) + .and_then(|u| { + let principal = windmill_common::users::username_to_own_permissioned_as(&u)?; + Some((u, principal)) + }) + { let new_principal = windmill_common::users::username_to_permissioned_as(&ru.new_username); // An agent records no address, so a workspace where the name is a member's own is // left to the per-workspace sweep: there the principal is that member. @@ -319,6 +327,17 @@ async fn rename_user( .bind(&old_username) .execute(&mut *tx) .await?; + // Where no member holds the name, `u/{name}` resolves to the superadmin with that + // `password.username`, so only a superadmin's rows there are theirs to move. + if is_super_admin { + move_run_as_principal( + &mut tx, + &old_principal, + &new_principal, + RunAsScope::WithoutMember(&old_username), + ) + .await?; + } sqlx::query!( "UPDATE app SET policy = jsonb_set(policy, ARRAY['on_behalf_of'], to_jsonb($1::text)) WHERE policy->>'on_behalf_of' = $2 AND policy->>'on_behalf_of_email' = $3", @@ -380,6 +399,190 @@ async fn rename_user( )) } +pub(crate) const TRIGGER_TABLES: [&str; 11] = [ + "http_trigger", + "websocket_trigger", + "kafka_trigger", + "postgres_trigger", + "mqtt_trigger", + "amqp_trigger", + "nats_trigger", + "sqs_trigger", + "gcp_trigger", + "azure_trigger", + "email_trigger", +]; + +enum RunAsScope<'a> { + Workspace(&'a str), + /// Every workspace where no member holds this username. + WithoutMember(&'a str), +} + +/// Moves the run-as principal of schedules, triggers and folder default rules. A row left on +/// the old principal no longer resolves: a schedule is disabled at its next push, a trigger +/// fails when it fires, and a folder rule rejects every runnable it matches. +/// `old_principal` must come from `username_to_own_permissioned_as`, never a group's. +async fn move_run_as_principal( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + old_principal: &str, + new_principal: &str, + scope: RunAsScope<'_>, +) -> error::Result<()> { + debug_assert!(!old_principal.starts_with(windmill_common::users::PERMISSIONED_AS_GROUP_PREFIX)); + let (scope_sql, scope_bind) = match scope { + RunAsScope::Workspace(w_id) => ("t.workspace_id = $3", w_id), + RunAsScope::WithoutMember(username) => ( + "NOT EXISTS (SELECT 1 FROM usr WHERE usr.workspace_id = t.workspace_id AND usr.username = $3)", + username, + ), + }; + // SAFETY: `table` comes from a hardcoded list and `scope_sql` from the match above. + for table in std::iter::once("schedule").chain(TRIGGER_TABLES) { + sqlx::query(&format!( + "UPDATE {table} t SET permissioned_as = $1 WHERE t.permissioned_as = $2 AND {scope_sql}" + )) + .bind(new_principal) + .bind(old_principal) + .bind(scope_bind) + .execute(&mut **tx) + .await?; + } + // The rules are ordered, first match wins, so the rewrite keeps their order. + sqlx::query(&format!( + r#"UPDATE folder t SET default_permissioned_as = ( + SELECT jsonb_agg( + CASE WHEN rule->>'permissioned_as' = $2 + THEN jsonb_set(rule, ARRAY['permissioned_as'], to_jsonb($1::text)) + ELSE rule END + ORDER BY ord) + FROM jsonb_array_elements(t.default_permissioned_as) WITH ORDINALITY AS r(rule, ord)) + WHERE t.default_permissioned_as @> jsonb_build_array(jsonb_build_object('permissioned_as', $2::text)) + AND {scope_sql}"# + )) + .bind(new_principal) + .bind(old_principal) + .bind(scope_bind) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// Moves the handlers that name a runnable under `old_prefix` (e.g. `u/alice/`) to the same path +/// under `new_prefix`, in the form each column stores: schedule handlers and the workspace +/// handlers' `path` carry a `script/` or `flow/` kind, a schedule's skip handler and a trigger's +/// error handler are bare script paths. A handler left on the old path fails exactly when it fires. +/// The Slack and Teams command scripts and the workspace's default app move the same way. +pub(crate) async fn move_handler_paths( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + w_id: &str, + old_prefix: &str, + new_prefix: &str, +) -> error::Result<()> { + // `starts_with` rather than `LIKE`/regex: a legacy email-shaped username carries `.` and `_`, + // which those would treat as wildcards and so rewrite another user's paths. + let moved = |col: &str| { + format!( + "CASE WHEN starts_with({col}, $1) THEN $2 || substr({col}, char_length($1) + 1) ELSE {col} END" + ) + }; + let moved_kind = |col: &str| { + format!( + "CASE WHEN starts_with({col}, 'script/' || $1) THEN 'script/' || $2 || substr({col}, char_length($1) + 8) + WHEN starts_with({col}, 'flow/' || $1) THEN 'flow/' || $2 || substr({col}, char_length($1) + 6) + ELSE {col} END" + ) + }; + let names_old = |col: &str| { + format!("(starts_with({col}, 'script/' || $1) OR starts_with({col}, 'flow/' || $1))") + }; + + // SAFETY: the interpolated column names are literals from this function. + sqlx::query(&format!( + "UPDATE schedule SET on_failure = {}, on_recovery = {}, on_success = {}, dynamic_skip = {} + WHERE workspace_id = $3 AND ({} OR {} OR {} OR starts_with(dynamic_skip, $1))", + moved_kind("on_failure"), + moved_kind("on_recovery"), + moved_kind("on_success"), + moved("dynamic_skip"), + names_old("on_failure"), + names_old("on_recovery"), + names_old("on_success"), + )) + .bind(old_prefix) + .bind(new_prefix) + .bind(w_id) + .execute(&mut **tx) + .await?; + + // SAFETY: `table` comes from the hardcoded `TRIGGER_TABLES`, not user input. + for table in TRIGGER_TABLES { + // A listener keeps the config it started with and its ping does not compare the handler, + // so clearing `server_id` is what makes it restart on the rewritten path. + let restart = match table { + "http_trigger" | "email_trigger" => "", + _ => ", server_id = NULL", + }; + sqlx::query(&format!( + "UPDATE {table} SET error_handler_path = {}{restart} + WHERE workspace_id = $3 AND starts_with(error_handler_path, $1)", + moved("error_handler_path"), + )) + .bind(old_prefix) + .bind(new_prefix) + .bind(w_id) + .execute(&mut **tx) + .await?; + } + + for setting in [ + "error_handler", + "success_handler", + "variable_expiration_handler", + ] { + let path = format!("({setting}->>'path')"); + sqlx::query(&format!( + "UPDATE workspace_settings SET {setting} = jsonb_set({setting}, '{{path}}', to_jsonb({})) + WHERE workspace_id = $3 AND {}", + moved_kind(&path), + names_old(&path), + )) + .bind(old_prefix) + .bind(new_prefix) + .bind(w_id) + .execute(&mut **tx) + .await?; + } + + // The command scripts are read with `RunnableRef::from_setting`, which takes a bare script + // path as well as a prefixed one, so both forms are moved. + let moved_command = |col: &str| { + format!( + "CASE WHEN {} THEN {} ELSE {} END", + names_old(col), + moved_kind(col), + moved(col) + ) + }; + let names_command = |col: &str| format!("({} OR starts_with({col}, $1))", names_old(col)); + sqlx::query(&format!( + "UPDATE workspace_settings + SET slack_command_script = {}, teams_command_script = {}, default_app = {} + WHERE workspace_id = $3 AND ({} OR {} OR starts_with(default_app, $1))", + moved_command("slack_command_script"), + moved_command("teams_command_script"), + moved("default_app"), + names_command("slack_command_script"), + names_command("teams_command_script"), + )) + .bind(old_prefix) + .bind(new_prefix) + .bind(w_id) + .execute(&mut **tx) + .await?; + Ok(()) +} + async fn update_username_in_workpsace<'c>( tx: &mut sqlx::Transaction<'c, sqlx::Postgres>, db: &DB, @@ -703,20 +906,6 @@ async fn update_username_in_workpsace<'c>( .execute(&mut **tx) .await?; - // Canonicalised through `username_to_permissioned_as`, not `'u/' || name`: an - // email-shaped username is stored bare, so the prefixed form would miss those rows and - // leave them naming a user that no longer exists. - let old_principal = windmill_common::users::username_to_permissioned_as(old_username); - let new_principal = windmill_common::users::username_to_permissioned_as(new_username); - sqlx::query!( - "UPDATE script SET on_behalf_of = $1 WHERE on_behalf_of = $2 AND workspace_id = $3", - &new_principal, - &old_principal, - w_id - ) - .execute(&mut **tx) - .await?; - // ---- flows ---- sqlx::query!( r#"INSERT INTO flow @@ -798,15 +987,6 @@ async fn update_username_in_workpsace<'c>( .execute(&mut **tx) .await?; - sqlx::query!( - "UPDATE flow SET on_behalf_of = $1 WHERE on_behalf_of = $2 AND workspace_id = $3", - &new_principal, - &old_principal, - w_id - ) - .execute(&mut **tx) - .await?; - // ---- draft ---- sqlx::query!( r#"UPDATE draft SET path = REGEXP_REPLACE(path,'u/' || $2 || '/(.*)','u/' || $1 || '/\1') WHERE path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#, @@ -825,18 +1005,6 @@ async fn update_username_in_workpsace<'c>( ).execute(&mut **tx) .await?; - // A draft carries the principal in its value, so a rename must reach it there too — - // deploying a draft that still names the old principal would be rejected as a pair naming - // somebody who no longer exists. Through the same canonical form as the columns above: a - // legacy `group-ops` username is named `g/ops`, which `'u/' || …` would never match. - sqlx::query!( - r#"UPDATE draft SET value = to_json(jsonb_set(to_jsonb(value), ARRAY['on_behalf_of'], to_jsonb($1::text))) WHERE value->>'on_behalf_of' = $2 AND workspace_id = $3"#, - &new_principal, - &old_principal, - w_id - ).execute(&mut **tx) - .await?; - // ---- app ---- sqlx::query!( r#"UPDATE app SET path = REGEXP_REPLACE(path,'u/' || $2 || '/(.*)','u/' || $1 || '/\1') WHERE path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#, @@ -868,7 +1036,7 @@ async fn update_username_in_workpsace<'c>( .await?; // An app draft carries a copy of the deployed policy, so the rename must reach it - // there too — same reason as the script/flow draft sweep above. + // there too — same reason as the script/flow draft sweep below. sqlx::query!( r#"UPDATE draft SET value = to_json(jsonb_set(to_jsonb(value), ARRAY['policy', 'on_behalf_of'], to_jsonb('u/' || $1))) WHERE typ IN ('app', 'raw_app') AND value->'policy'->>'on_behalf_of' = ('u/' || $2) AND workspace_id = $3"#, new_username, @@ -937,6 +1105,78 @@ async fn update_username_in_workpsace<'c>( .execute(&mut **tx) .await?; + // ---- triggers ---- + // `starts_with` rather than `LIKE`/regex: a legacy email-shaped username carries `.` and `_`, + // which those would treat as wildcards and so rewrite another user's paths. + // SAFETY: `table` comes from the hardcoded `TRIGGER_TABLES`, not user input. + for table in TRIGGER_TABLES { + sqlx::query(&format!( + "UPDATE {table} SET + path = CASE WHEN starts_with(path, 'u/' || $2 || '/') + THEN 'u/' || $1 || substr(path, char_length($2) + 3) ELSE path END, + script_path = CASE WHEN starts_with(script_path, 'u/' || $2 || '/') + THEN 'u/' || $1 || substr(script_path, char_length($2) + 3) ELSE script_path END, + edited_by = CASE WHEN edited_by = $2 THEN $1 ELSE edited_by END, + extra_perms = CASE WHEN extra_perms ? ('u/' || $2) + THEN extra_perms - ('u/' || $2) || jsonb_build_object('u/' || $1, extra_perms->('u/' || $2)) + ELSE extra_perms END + WHERE workspace_id = $3 + AND (starts_with(path, 'u/' || $2 || '/') OR starts_with(script_path, 'u/' || $2 || '/') + OR edited_by = $2 OR extra_perms ? ('u/' || $2))" + )) + .bind(new_username) + .bind(old_username) + .bind(w_id) + .execute(&mut **tx) + .await?; + } + + // ---- run-as principal ---- + // Canonicalised, not `'u/' || name`: an email-shaped username is stored bare, so the + // prefixed form would miss those rows and leave them naming a user that no longer exists. + if let Some(old_principal) = + windmill_common::users::username_to_own_permissioned_as(old_username) + { + let new_principal = windmill_common::users::username_to_permissioned_as(new_username); + sqlx::query!( + "UPDATE script SET on_behalf_of = $1 WHERE on_behalf_of = $2 AND workspace_id = $3", + &new_principal, + &old_principal, + w_id + ) + .execute(&mut **tx) + .await?; + + sqlx::query!( + "UPDATE flow SET on_behalf_of = $1 WHERE on_behalf_of = $2 AND workspace_id = $3", + &new_principal, + &old_principal, + w_id + ) + .execute(&mut **tx) + .await?; + + // A draft carries the principal in its value: deploying one that still names the old + // principal would be rejected as a pair naming somebody who no longer exists. + sqlx::query!( + r#"UPDATE draft SET value = to_json(jsonb_set(to_jsonb(value), ARRAY['on_behalf_of'], to_jsonb($1::text))) WHERE value->>'on_behalf_of' = $2 AND workspace_id = $3"#, + &new_principal, + &old_principal, + w_id + ).execute(&mut **tx) + .await?; + + move_run_as_principal( + tx, + &old_principal, + &new_principal, + RunAsScope::Workspace(w_id), + ) + .await?; + } + + move_handler_paths(tx, w_id, &old_prefix, &new_prefix).await?; + // ---- group_ ---- sqlx::query!( diff --git a/backend/windmill-api/src/workspace_dependencies.rs b/backend/windmill-api/src/workspace_dependencies.rs index 170006f44a..ec9db2e514 100644 --- a/backend/windmill-api/src/workspace_dependencies.rs +++ b/backend/windmill-api/src/workspace_dependencies.rs @@ -48,31 +48,37 @@ async fn create( } let dep_path = WorkspaceDependencies::to_path(&nwd.name, nwd.language)?; - let email = authed.email.clone(); - let username = authed.username.clone(); - let id = nwd - .create( - ( - authed.email, - username_to_permissioned_as(&authed.username), - authed.username, - ), - db.clone(), + // The first default dependencies of a workspace rebuild its whole dependency map, which can + // outlast a client's timeout. A disconnect drops this handler; spawned, the rebuild still + // completes and records that it ran, so the client's retry does not start it over. + let id = tokio::spawn(async move { + let id = nwd + .create( + ( + authed.email.clone(), + username_to_permissioned_as(&authed.username), + authed.username.clone(), + ), + db.clone(), + ) + .await?; + + handle_deployment_metadata( + &authed.email, + &authed.username, + &db, + &w_id, + DeployedObject::WorkspaceDependencies { path: dep_path }, + None, + true, + None, ) .await?; - - handle_deployment_metadata( - &email, - &username, - &db, - &w_id, - DeployedObject::WorkspaceDependencies { path: dep_path }, - None, - true, - None, - ) - .await?; + Ok::<_, error::Error>(id) + }) + .await + .map_err(|e| error::Error::internal_err(format!("creating workspace dependencies: {e}")))??; Ok((StatusCode::CREATED, format!("{}", id))) } diff --git a/backend/windmill-api/src/workspace_settings_document.rs b/backend/windmill-api/src/workspace_settings_document.rs index bcf7022184..a670340706 100644 --- a/backend/windmill-api/src/workspace_settings_document.rs +++ b/backend/windmill-api/src/workspace_settings_document.rs @@ -41,7 +41,8 @@ use crate::db::ApiAuthed; pub const SENSITIVE_UNCHANGED: &str = "__SENSITIVE_AND_UNCHANGED__"; use windmill_common::variables::SETTINGS_ENCRYPTED_PREFIX as ENCRYPTED_PREFIX; -const SECRET_KEYS: &[&str] = &["slack_oauth_client_secret"]; +/// The webhook URL is a secret because it usually carries the receiver's token. +const SECRET_KEYS: &[&str] = &["webhook", "slack_oauth_client_secret"]; #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Default)] #[serde(rename_all = "snake_case")] @@ -366,17 +367,21 @@ pub async fn load_settings_document( .fetch_one(&mut *conn) .await?; - let slack_oauth_client_secret = match (row.slack_oauth_client_secret, secrets) { - (Some(s), SecretMode::Redacted) if !s.is_empty() => Some(SENSITIVE_UNCHANGED.to_string()), - (Some(s), SecretMode::Encrypted) if !s.is_empty() => { - let mc = build_crypt(db, w_id).await?; - Some(format!( - "{ENCRYPTED_PREFIX}{}", - mc.encrypt_str_deterministic(&s) - )) - } + let mc = match secrets { + SecretMode::Encrypted => Some(build_crypt(db, w_id).await?), + _ => None, + }; + let secret = |v: Option<String>| match (v, &mc) { + (Some(s), _) if s.is_empty() => Some(s), + (Some(s), Some(mc)) => Some(format!( + "{ENCRYPTED_PREFIX}{}", + mc.encrypt_str_deterministic(&s) + )), + (Some(_), None) if secrets == SecretMode::Redacted => Some(SENSITIVE_UNCHANGED.to_string()), (s, _) => s, }; + let webhook = secret(row.webhook); + let slack_oauth_client_secret = secret(row.slack_oauth_client_secret); let has_permissions = row .datatable @@ -413,7 +418,7 @@ pub async fn load_settings_document( // added since is always written, so a pulled file states it and from then on manages it. let entries: [(&str, Option<Value>, bool); 33] = [ ("auto_invite", row.auto_invite, false), - ("webhook", row.webhook.map(Value::String), false), + ("webhook", webhook.map(Value::String), false), ("webhook_events", row.webhook_events.map(|e| json!(e)), true), ("error_handler", row.error_handler, true), ("success_handler", row.success_handler, true), @@ -2252,25 +2257,27 @@ mod tests { #[test] fn secrets_keep_their_value_for_the_placeholder_and_a_foreign_key() { let mc = WorkspaceCrypt::new("k"); - let ours = format!( - "{ENCRYPTED_PREFIX}{}", - mc.encrypt_str_deterministic("sekret") - ); let theirs = format!( "{ENCRYPTED_PREFIX}{}", WorkspaceCrypt::new("other").encrypt_str_deterministic("x") ); - for secret in [SENSITIVE_UNCHANGED.to_string(), ours, theirs.clone()] { - let p = plan_document( - current(), - doc(json!({ "slack_oauth_client_secret": secret })), - false, - &mc, - &DatatableNames::default(), - ) - .unwrap(); - assert!(p.changes.is_empty(), "{secret}: {:?}", keys(&p)); - assert_eq!(p.warnings.len(), usize::from(secret == theirs)); + for (key, stored) in [ + ("slack_oauth_client_secret", "sekret"), + ("webhook", "https://a"), + ] { + let ours = format!("{ENCRYPTED_PREFIX}{}", mc.encrypt_str_deterministic(stored)); + for secret in [SENSITIVE_UNCHANGED.to_string(), ours, theirs.clone()] { + let p = plan_document( + current(), + doc(json!({ key: secret })), + false, + &mc, + &DatatableNames::default(), + ) + .unwrap(); + assert!(p.changes.is_empty(), "{key} {secret}: {:?}", keys(&p)); + assert_eq!(p.warnings.len(), usize::from(secret == theirs)); + } } } diff --git a/backend/windmill-common/src/auth.rs b/backend/windmill-common/src/auth.rs index 330566f5f3..b91bdf68a8 100644 --- a/backend/windmill-common/src/auth.rs +++ b/backend/windmill-common/src/auth.rs @@ -413,6 +413,7 @@ impl From<JobPerms> for Authed { scopes: None, token_prefix: None, mcp_client: value.mcp_client, + capabilities: None, } } } @@ -606,6 +607,7 @@ async fn fetch_authed_from_permissioned_as_inner( scopes: None, token_prefix: None, mcp_client: None, + capabilities: None, }) } else { let groups = vec![name.to_string()]; @@ -620,6 +622,7 @@ async fn fetch_authed_from_permissioned_as_inner( scopes: None, token_prefix: None, mcp_client: None, + capabilities: None, }) } } else { @@ -642,6 +645,7 @@ async fn fetch_authed_from_permissioned_as_inner( scopes: None, token_prefix: None, mcp_client: None, + capabilities: None, }) } } diff --git a/backend/windmill-common/src/db.rs b/backend/windmill-common/src/db.rs index edda7fca07..6093ffa76a 100644 --- a/backend/windmill-common/src/db.rs +++ b/backend/windmill-common/src/db.rs @@ -1,6 +1,6 @@ use sqlx::{Acquire, PgConnection, PgExecutor, Pool, Postgres, Transaction}; -use crate::audit::AuditAuthor; +use crate::{audit::AuditAuthor, roles::RoleCapabilities}; pub type DB = Pool<Postgres>; @@ -22,6 +22,8 @@ pub struct Authed { pub token_prefix: Option<String>, /// See `ApiAuthed::mcp_client`. pub mcp_client: Option<String>, + /// See `ApiAuthed::capabilities`. + pub capabilities: Option<RoleCapabilities>, } impl Authed { @@ -35,6 +37,7 @@ impl Authed { folders: &self.folders, scopes: &self.scopes, token_prefix: &self.token_prefix, + capabilities: self.capabilities, } } } @@ -50,6 +53,7 @@ pub struct AuthedRef<'a> { pub folders: &'a Vec<(String, bool, bool)>, pub scopes: &'a Option<Vec<String>>, pub token_prefix: &'a Option<String>, + pub capabilities: Option<RoleCapabilities>, } impl Authable for AuthedRef<'_> { @@ -65,6 +69,9 @@ impl Authable for AuthedRef<'_> { fn is_operator(&self) -> bool { *self.is_operator } + fn capabilities(&self) -> Option<RoleCapabilities> { + self.capabilities + } fn groups(&self) -> &[String] { self.groups } @@ -86,6 +93,9 @@ pub trait Authable { fn username(&self) -> &str; fn is_admin(&self) -> bool; fn is_operator(&self) -> bool; + /// The role's capabilities as read for the request, `None` if they were not read. Read them + /// through `roles::caller_capabilities`, never directly. + fn capabilities(&self) -> Option<RoleCapabilities>; fn groups(&self) -> &[String]; fn folders(&self) -> &[(String, bool, bool)]; fn scopes(&self) -> Option<&[String]>; @@ -100,6 +110,10 @@ impl Authable for Authed { self.is_operator } + fn capabilities(&self) -> Option<RoleCapabilities> { + self.capabilities + } + fn groups(&self) -> &[String] { &self.groups } diff --git a/backend/windmill-common/src/flow_conversations.rs b/backend/windmill-common/src/flow_conversations.rs index 12b3daf2ec..e85ef13be3 100644 --- a/backend/windmill-common/src/flow_conversations.rs +++ b/backend/windmill-common/src/flow_conversations.rs @@ -19,6 +19,32 @@ const MEMORY_ID_NAMESPACE: Uuid = Uuid::from_u128(0x6f1c2d4e_8a3b_5c7d_9e0f_1a2b /// would otherwise list every anonymous visitor's. pub const ANONYMOUS_CONVERSATION_OWNER: &str = "anonymous"; +/// Cancels the background jobs a turn was handed (`ai_memory_turn.handed_jobs`) and ended before +/// its agent adopted, with every job under them: a nested agent among them may have background +/// jobs of its own, and nothing else cancels any of them once their old agent has ended. +pub async fn cancel_unadopted_handed_jobs<'e, E: sqlx::PgExecutor<'e>>( + executor: E, + handed_jobs: &serde_json::Value, +) -> Result<u64> { + let cancelled = sqlx::query!( + "WITH RECURSIVE tree AS ( + SELECT (b->>'job_id')::uuid AS id + FROM jsonb_each($1::jsonb) s, jsonb_array_elements(s.value) b + UNION + SELECT j.id FROM v2_job j JOIN tree t ON j.parent_job = t.id + ) + UPDATE v2_job_queue q + SET canceled_by = 'monitor', scheduled_for = now(), suspend = 0, + canceled_reason = 'the turn its AI agent was handed to ended before taking it' + FROM tree WHERE q.id = tree.id AND q.canceled_by IS NULL", + handed_jobs + ) + .execute(executor) + .await? + .rows_affected(); + Ok(cancelled) +} + /// Memory is stored and carried in `flow_status.memory_id` as a uuid, which names the same memory /// wherever it is passed, as a chat conversation id must. Any other string names a memory through a /// name-based (v5) uuid scoped to its workspace and flow, so the same key in two flows or two @@ -139,6 +165,23 @@ async fn refuse_running_turn( else { return Ok(()); }; + // A turn whose agent parked as its run's last step hands over to this one when the run + // claims the memory id (`hand_over_parked_turn`, which holds the same condition). + let parked = sqlx::query_scalar!( + r#"SELECT EXISTS (SELECT 1 FROM ai_agent_checkpoint c + JOIN v2_job_queue q ON q.id = c.job_id JOIN v2_job j ON j.id = c.job_id + JOIN v2_job_status s ON s.id = $1 + WHERE j.parent_job = $1 + AND (s.flow_status->>'step')::int = jsonb_array_length(s.flow_status->'modules') - 1 + AND s.flow_status->'modules'->-1->>'job' = c.job_id::text + AND q.suspend > 0 AND q.suspend_until IS NOT NULL) AS "parked!""#, + turn.job_id + ) + .fetch_one(&mut **tx) + .await?; + if parked { + return Ok(()); + } // A JSON body, so a chat client can follow the running turn instead of failing. Err(crate::error::Error::Generic( axum::http::StatusCode::CONFLICT, diff --git a/backend/windmill-common/src/flows.rs b/backend/windmill-common/src/flows.rs index a428a32116..7c13f33fbd 100644 --- a/backend/windmill-common/src/flows.rs +++ b/backend/windmill-common/src/flows.rs @@ -245,6 +245,9 @@ pub struct ComposedFlowRefs { pub tags: Vec<String>, /// Every workspace runnable a step references, as `(is_flow, path)`. pub runnables: Vec<(bool, String)>, + /// Every Hub script or flow a step references, for the caller to check it may name: a Hub + /// path has no workspace row the readability check of `runnables` could find. + pub hub_runnables: Vec<RunnableRef>, /// Version-pinned script steps, as `(path, hash)`. pub pinned_scripts: Vec<(String, ScriptHash)>, /// The `ai_agent` resources that agent steps link. @@ -345,16 +348,14 @@ fn check_module_value_is_composition_only( } FlowModuleValue::Identity => {} FlowModuleValue::Script { path, hash, tag_override, .. } => { - check_composable_path(path, false, id)?; push_tag(tag_override); - refs.runnables.push((false, path.clone())); + push_runnable(refs, path, false)?; if let Some(hash) = hash { refs.pinned_scripts.push((path.clone(), *hash)); } } FlowModuleValue::Flow { path, .. } => { - check_composable_path(path, true, id)?; - refs.runnables.push((true, path.clone())); + push_runnable(refs, path, true)?; } FlowModuleValue::ForloopFlow { modules, modules_node, .. } | FlowModuleValue::WhileloopFlow { modules, modules_node, .. } => { @@ -427,17 +428,15 @@ fn refused(id: &str, what: &str) -> Error { )) } -fn check_composable_path(path: &str, is_flow: bool, id: &str) -> Result<(), Error> { - if !path.is_empty() - && RunnableRef::from_path(path, is_flow)? - .path() - .starts_with("hub/") - { - return Err(Error::PermissionDenied(format!( - "Step {id}: hub runnables are not available to operators with builder rights. Deploy \ - it to the workspace first." - ))); +fn push_runnable(refs: &mut ComposedFlowRefs, path: &str, is_flow: bool) -> Result<(), Error> { + if !path.is_empty() { + let runnable = RunnableRef::from_path(path, is_flow)?; + if runnable.path().starts_with("hub/") { + refs.hub_runnables.push(runnable); + return Ok(()); + } } + refs.runnables.push((is_flow, path.to_string())); Ok(()) } @@ -595,22 +594,22 @@ mod tests { } #[test] - fn composition_check_rejects_hub_runnables() { + fn composition_check_collects_hub_runnables() { for (kind, path) in [ ("script", "hub/1234/thing"), ("script", "/hub/1234/thing"), ("flow", "hub/flows/1234/thing"), ("flow", "/hub/flows/1234/thing"), - // Parses as a workspace flow path, so only the Hub check refuses it. + // Parses as a workspace flow path, so only the path prefix marks it as Hub. ("flow", "hub/1234/thing"), ] { let value = serde_json::json!({"modules": [{"id": "a", "value": {"type": kind, "path": path}}]}); - assert!( - matches!( - check_flow_is_composition_only(&flow(value)), - Err(Error::PermissionDenied(_)) - ), + let refs = check_flow_is_composition_only(&flow(value)).unwrap(); + assert!(refs.runnables.is_empty(), "{kind} {path}"); + assert_eq!( + refs.hub_runnables, + vec![RunnableRef::from_path(path, kind == "flow").unwrap()], "{kind} {path}" ); } diff --git a/backend/windmill-common/src/git_sync_oss.rs b/backend/windmill-common/src/git_sync_oss.rs index 4c7de4fa7b..ef97bc249b 100644 --- a/backend/windmill-common/src/git_sync_oss.rs +++ b/backend/windmill-common/src/git_sync_oss.rs @@ -143,6 +143,40 @@ pub fn prepend_token_to_github_url( )) } +/// Make the URL an admin just saved on an app-backed `git_repository` +/// resource the only repository the GitHub App installation serves non-admins +/// through it, or revoke it when the save names none. Run in the admin's write +/// transaction, after a write that carries the value, so the approval commits +/// with the value it approves and no later write can be overtaken by it. +/// +/// Only a literal URL is approved. A `$var:` resolves to whatever its owner +/// sets, which the admin never saw, so such a resource stays admin-only. +pub async fn approve_github_app_repo( + tx: &mut sqlx::PgConnection, + w_id: &str, + path: &str, +) -> crate::error::Result<()> { + sqlx::query!( + "DELETE FROM github_app_repo_approval WHERE workspace_id = $1 AND path = $2", + w_id, + path + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "INSERT INTO github_app_repo_approval (workspace_id, path, url) + SELECT workspace_id, path, value->>'url' FROM resource + WHERE workspace_id = $1 AND path = $2 + AND value->'is_github_app' = 'true'::jsonb + AND left(value->>'url', 1) <> '$'", + w_id, + path + ) + .execute(&mut *tx) + .await?; + Ok(()) +} + #[cfg(test)] mod tests { use super::sanitize_git_url; diff --git a/backend/windmill-common/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index 8985ef3fde..03d0edf8d6 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -471,7 +471,7 @@ pub const ALERT_CONFIG_SETTING: &str = "alert_job_queue_waiting"; /// The instance's workspace roles (EE), a list of `crate::roles::RoleDefinition`. pub const WORKSPACE_ROLES_SETTING: &str = "workspace_roles"; -// Workspace fairness: cloud-only mechanism that caps any single workspace at +// Workspace fairness (Enterprise): caps any single workspace at // `workspace_fairness_max_percent`% of the shared worker pool once it has been // occupying it for more than `workspace_fairness_duration_secs` seconds. See // `windmill-queue/src/workspace_fairness.rs`. diff --git a/backend/windmill-common/src/instance_config.rs b/backend/windmill-common/src/instance_config.rs index 93eb046a37..41317e41d8 100644 --- a/backend/windmill-common/src/instance_config.rs +++ b/backend/windmill-common/src/instance_config.rs @@ -1023,6 +1023,10 @@ pub struct WorkerGroupConfig { /// The group listens to its tags suffixed with the dev workspace tag suffix, and only to them. #[serde(skip_serializing_if = "Option::is_none")] pub serves_dev_workspaces: Option<bool>, + /// Workers of the group pull only while workspace fairness caps a workspace, and only jobs + /// of the workspaces it does not cap. + #[serde(skip_serializing_if = "Option::is_none")] + pub fairness_reserve: Option<bool>, /// Object store this group's dependency cache uses instead of the instance one. Same shape /// as the instance `object_store_cache_config`. #[serde(skip_serializing_if = "Option::is_none")] diff --git a/backend/windmill-common/src/jobs.rs b/backend/windmill-common/src/jobs.rs index 8cbafe9ebb..2e5dafe1b2 100644 --- a/backend/windmill-common/src/jobs.rs +++ b/backend/windmill-common/src/jobs.rs @@ -148,8 +148,62 @@ pub fn resolve_delete_after_secs( } } +/// Who chose the path a job is resolved from. Deliberately has no default: every caller must say +/// which it is. +pub enum RunOrigin<'a> { + /// The person who chose the path, whose rights it is held to; usually, not always, the + /// identity the job runs as (a preview on behalf of another user, a run-as script). + NamedBy(AuthedRef<'a>), + /// The path is read from a row whose write was checked when it was saved, so it is not + /// re-checked here. Choose it only when that save-time check exists. + Deployed, +} + +/// [`RunOrigin`] for a function that is handed the identity of the person who would have named +/// the path: `Caller` resolves to `NamedBy` that identity. Never pass `Caller` with an identity +/// other than that person's (a trigger's run-as user). +#[derive(Clone, Copy)] +pub enum ChosenBy { + Caller, + Deployed, +} + +impl ChosenBy { + pub fn origin<'a>(self, caller: AuthedRef<'a>) -> RunOrigin<'a> { + match self { + ChosenBy::Caller => RunOrigin::NamedBy(caller), + ChosenBy::Deployed => RunOrigin::Deployed, + } + } +} + +/// Refuses a Hub script or flow named by a member whose role cannot write code, preset handlers +/// excepted. Gated on the path, not `hub_id()`: a flow at `hub/123` has none. +pub async fn check_can_name_runnable( + origin: &RunOrigin<'_>, + runnable: &RunnableRef, + db: &DB, + w_id: &str, +) -> error::Result<()> { + let RunOrigin::NamedBy(authed) = origin else { + return Ok(()); + }; + if !runnable.path().starts_with("hub/") + || runnable.preset_handler().is_some() + || crate::roles::caller_capabilities(db, w_id, authed) + .await? + .code + { + return Ok(()); + } + Err(Error::PermissionDenied( + "Hub scripts and flows require a role that can write code. Ask a developer to deploy it to the workspace.".to_string(), + )) +} + pub async fn script_path_to_payload<'e>( script: &RunnableRef, + origin: RunOrigin<'_>, db_authed: Option<UserDbWithAuthed<'e, AuthedRef<'e>>>, db: DB, w_id: &str, @@ -162,6 +216,7 @@ pub async fn script_path_to_payload<'e>( Option<i32>, Option<OnBehalfOf>, )> { + check_can_name_runnable(&origin, script, &db, w_id).await?; let script_path = script.path(); let (job_payload, tag, delete_after_use, delete_after_secs, script_timeout, on_behalf_of) = if let Some(hub_id) = script.hub_id() { @@ -247,12 +302,14 @@ pub async fn script_path_to_payload<'e>( pub async fn runnable_ref_to_payload( runnable: &RunnableRef, + origin: RunOrigin<'_>, db: &DB, w_id: &str, ) -> Result<(JobPayload, Option<String>, Option<OnBehalfOf>), Error> { let (payload, tag, _, _, _, on_behalf_of) = if !runnable.is_flow() { - script_path_to_payload(runnable, None, db.clone(), w_id, Some(true)).await? + script_path_to_payload(runnable, origin, None, db.clone(), w_id, Some(true)).await? } else { + check_can_name_runnable(&origin, runnable, db, w_id).await?; let path = runnable.path().to_string(); if let Some(hub_id) = runnable.hub_id() { let hub_flow = get_full_hub_flow_by_id(hub_id, &HTTP_CLIENT, Some(db)).await?; diff --git a/backend/windmill-common/src/min_version.rs b/backend/windmill-common/src/min_version.rs index 9005ab834a..63b3c7742a 100644 --- a/backend/windmill-common/src/min_version.rs +++ b/backend/windmill-common/src/min_version.rs @@ -39,6 +39,15 @@ pub const MIN_VERSION_SUPPORTS_VARIABLE_VALUE_WIDENING: VC = // to accept one once this is met. Only worker versions are seen here, not servers. Must name // the release this ships in. pub const MIN_VERSION_SUPPORTS_ED25519_LICENSE: VC = vc(1, 838, 0, "Ed25519 license keys"); +// `volume:ro` mounts pull without the volume's lease and rely on every writer marking its +// write in `volume.generation`. A worker that predates it writes without that mark, so a +// lease-free pull overlapping its write would keep a mix of old and new files; until the +// whole fleet has it, read-only mounts take the lease. Must name the release this ships in. +pub const MIN_VERSION_SUPPORTS_LEASE_FREE_VOLUMES: VC = vc(1, 872, 0, "Lease-free volume reads"); +// A worker that predates `FlowStatus::test_subflows` ignores it and runs the deployed subflow, +// so a step the test mocks would run for real. Must name the release this ships in. +pub const MIN_VERSION_SUPPORTS_FLOW_TEST_SUBFLOWS: VC = + vc(1, 879, 0, "Overriding steps inside subflows in flow tests"); pub const MIN_VERSION_SUPPORTS_NODE_DEBOUNCING: VC = vc(1, 658, 0, "Flow node debouncing"); pub const MIN_VERSION_SUPPORTS_TOKEN_HASH: VC = vc(1, 659, 0, "Token hash storage"); pub const MIN_VERSION_SUPPORTS_SYNC_JOBS_DEBOUNCING: VC = vc(1, 602, 0, "Sync jobs debouncing"); diff --git a/backend/windmill-common/src/oidc_oss.rs b/backend/windmill-common/src/oidc_oss.rs index 60ef4da687..a9277b3d58 100644 --- a/backend/windmill-common/src/oidc_oss.rs +++ b/backend/windmill-common/src/oidc_oss.rs @@ -99,6 +99,7 @@ pub enum OidcCaller { Sqs, Bedrock, Anthropic, + GoogleVertex, } #[cfg(not(feature = "private"))] diff --git a/backend/windmill-common/src/query_builders.rs b/backend/windmill-common/src/query_builders.rs index be608ebf34..145228abdf 100644 --- a/backend/windmill-common/src/query_builders.rs +++ b/backend/windmill-common/src/query_builders.rs @@ -608,7 +608,8 @@ pub fn build_parameters(columns: &[SimpleColumn], db_type: DbType) -> String { DbType::Postgresql => format!("-- ${} {} ({})", i + 1, col.field, base_type), DbType::Mysql => format!("-- :{} ({})", col.field, base_type), DbType::MsSqlServer => { - format!("-- @p{} {} ({})", i + 1, col.field, base_type) + // The executor binds `@P1..`; under a case-sensitive collation `@p1` is undeclared. + format!("-- @P{} {} ({})", i + 1, col.field, base_type) } DbType::Snowflake => format!("-- ? {} ({})", col.field, base_type), DbType::Bigquery => format!("-- @{} ({})", col.field, base_type), @@ -1031,7 +1032,7 @@ pub fn make_select_query_with_joins( let escaped = escape_sql_literal(&col.field); let quoted = qi(&col.field, db_type); format!( - "\n(CASE WHEN @p4 = '{}' AND @p5 = 0 THEN {} END) ASC,\n(CASE WHEN @p4 = '{}' AND @p5 = 1 THEN {} END) DESC", + "\n(CASE WHEN @P4 = '{}' AND @P5 = 0 THEN {} END) ASC,\n(CASE WHEN @P4 = '{}' AND @P5 = 1 THEN {} END) DESC", escaped, quoted, escaped, quoted ) }) @@ -1054,11 +1055,11 @@ pub fn make_select_query_with_joins( let quicksearch = if !search_clause.is_empty() { format!( - " (@p3 = '' OR CONCAT({}) LIKE '%' + @p3 + '%')", + " (@P3 = '' OR CONCAT({}) LIKE '%' + @P3 + '%')", search_clause ) } else { - " (@p3 = '')".to_string() + " (@P3 = '')".to_string() }; query.push_str(&format!( @@ -1074,7 +1075,7 @@ pub fn make_select_query_with_joins( quicksearch )); query.push_str(&format!(" ORDER BY {}", order_by)); - query.push_str(" OFFSET @p2 ROWS FETCH NEXT @p1 ROWS ONLY"); + query.push_str(" OFFSET @P2 ROWS FETCH NEXT @P1 ROWS ONLY"); Ok(query) } DbType::Bigquery => { @@ -1267,11 +1268,11 @@ pub fn make_count_query_with_joins( DbType::MsSqlServer => { if !filtered_columns.is_empty() { quicksearch_condition.push_str(&format!( - "(@p1 = '' OR CONCAT({}) LIKE '%' + @p1 + '%')", + "(@P1 = '' OR CONCAT({}) LIKE '%' + @P1 + '%')", filtered_columns.join(", ") )); } else { - quicksearch_condition.push_str("(@p1 = '' OR 1 = 1)"); + quicksearch_condition.push_str("(@P1 = '' OR 1 = 1)"); } query.push_str(&format!("SELECT COUNT(*) as count FROM {}", source)); } @@ -1430,7 +1431,7 @@ pub fn make_delete_query(table: &str, columns: &[ColumnDef], db_type: DbType) -> .enumerate() .map(|(i, c)| { let qf = qi(&c.field, db_type); - let param = format!("@p{}", i + 1); + let param = format!("@P{}", i + 1); mssql_eq_condition(&qf, ¶m, &c.datatype) }) .collect::<Vec<_>>() @@ -1547,7 +1548,7 @@ fn format_insert_values(columns: &[ColumnDef], db_type: DbType, start_index: usi .map(|(i, c)| match db_type { DbType::Mysql => format!(":{}", c.field), DbType::Postgresql => pg_value(&format!("${}", start_index + i), &c.datatype), - DbType::MsSqlServer => format!("@p{}", start_index + i), + DbType::MsSqlServer => format!("@P{}", start_index + i), DbType::Snowflake => "?".to_string(), DbType::Bigquery => format!("@{}", c.field), DbType::Duckdb => format!("${}", c.field), @@ -1756,13 +1757,13 @@ pub fn make_update_query( .enumerate() .map(|(i, c)| { let qf = qi(&c.field, db_type); - let param = format!("@p{}", i + 2); + let param = format!("@P{}", i + 2); mssql_eq_condition(&qf, ¶m, &c.datatype) }) .collect::<Vec<_>>() .join("\n AND "); query.push_str(&format!( - "\nUPDATE {} SET {} = @p1 \nWHERE {}", + "\nUPDATE {} SET {} = @P1 \nWHERE {}", qt, qcol, conditions )); } @@ -3213,7 +3214,7 @@ mod tests { simple_col("name", "nvarchar(50)"), ]; let result = build_parameters(&cols, DbType::MsSqlServer); - assert_eq!(result, "-- @p1 limit (int)\n-- @p2 name (nvarchar)"); + assert_eq!(result, "-- @P1 limit (int)\n-- @P2 name (nvarchar)"); } #[test] @@ -3384,8 +3385,8 @@ mod tests { make_select_query("my_table", &cols, None, DbType::MsSqlServer, None, None).unwrap(); assert!(result.contains("SELECT [id], [name] FROM [my_table]")); - assert!(result.contains("@p3 = '' OR CONCAT([id], [name]) LIKE '%' + @p3 + '%'")); - assert!(result.contains("OFFSET @p2 ROWS FETCH NEXT @p1 ROWS ONLY")); + assert!(result.contains("@P3 = '' OR CONCAT([id], [name]) LIKE '%' + @P3 + '%'")); + assert!(result.contains("OFFSET @P2 ROWS FETCH NEXT @P1 ROWS ONLY")); } #[test] @@ -3395,7 +3396,7 @@ mod tests { make_select_query("my_table", &cols, None, DbType::MsSqlServer, None, None).unwrap(); // text type should be excluded from ORDER BY - assert!(!result.contains("@p4 = 'body'")); + assert!(!result.contains("@P4 = 'body'")); // text type should be excluded from search clause assert!(!result.contains("CONCAT([id], [body])")); assert!(result.contains("CONCAT([id])")); @@ -3592,7 +3593,7 @@ mod tests { let result = make_count_query(DbType::MsSqlServer, "my_table", None, &cols, None).unwrap(); assert!(result.contains("SELECT COUNT(*) as count FROM [my_table]")); - assert!(result.contains("(@p1 = '' OR CONCAT([id], [name]) LIKE '%' + @p1 + '%')")); + assert!(result.contains("(@P1 = '' OR CONCAT([id], [name]) LIKE '%' + @P1 + '%')")); } // ----------------------------------------------------------------------- @@ -3761,10 +3762,10 @@ mod tests { let cols = vec![col("id", "int"), col("name", "nvarchar")]; let result = make_delete_query("my_table", &cols, DbType::MsSqlServer); - assert!(result.contains("-- @p1 id (int)\n-- @p2 name (nvarchar)")); + assert!(result.contains("-- @P1 id (int)\n-- @P2 name (nvarchar)")); assert!(result.contains("DELETE FROM [my_table]")); - assert!(result.contains("(@p1 IS NULL AND [id] IS NULL OR [id] = @p1)")); - assert!(result.contains("(@p2 IS NULL AND [name] IS NULL OR [name] = @p2)")); + assert!(result.contains("(@P1 IS NULL AND [id] IS NULL OR [id] = @P1)")); + assert!(result.contains("(@P2 IS NULL AND [name] IS NULL OR [name] = @P2)")); } #[test] @@ -3825,7 +3826,7 @@ mod tests { let cols = vec![col("id", "int"), col("name", "nvarchar")]; let result = make_insert_query("my_table", &cols, DbType::MsSqlServer).unwrap(); - assert!(result.contains("INSERT INTO [my_table] ([id], [name]) VALUES (@p1, @p2)")); + assert!(result.contains("INSERT INTO [my_table] ([id], [name]) VALUES (@P1, @P2)")); } #[test] @@ -3984,8 +3985,8 @@ mod tests { let where_cols = vec![simple_col("id", "int")]; let result = make_update_query("my_table", &update_col, &where_cols, DbType::MsSqlServer); - assert!(result.contains("UPDATE [my_table] SET [name] = @p1")); - assert!(result.contains("(@p2 IS NULL AND [id] IS NULL OR [id] = @p2)")); + assert!(result.contains("UPDATE [my_table] SET [name] = @P1")); + assert!(result.contains("(@P2 IS NULL AND [id] IS NULL OR [id] = @P2)")); } #[test] diff --git a/backend/windmill-common/src/roles.rs b/backend/windmill-common/src/roles.rs index c2de5520c0..f1db372cf3 100644 --- a/backend/windmill-common/src/roles.rs +++ b/backend/windmill-common/src/roles.rs @@ -27,7 +27,9 @@ pub const DEVELOPER_ROLE: &str = "developer"; pub const OPERATOR_ROLE: &str = "operator"; /// How much of a kind of runnable a role may author. -#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default, PartialOrd, Ord)] +#[derive( + Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, Default, PartialOrd, Ord, +)] #[serde(rename_all = "snake_case")] pub enum AuthorLevel { #[default] @@ -41,7 +43,7 @@ pub enum AuthorLevel { /// Pages a role sees. Not enforced: hiding a page never stopped an API call, and the enforced /// rights are the other fields of [`RoleCapabilities`]. -#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct RoleVisibility { pub runs: bool, pub schedules: bool, @@ -82,11 +84,13 @@ impl RoleVisibility { }; } -#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct RoleCapabilities { /// Author scripts and run code of one's own on a worker: script previews, dependency jobs, /// dynamic selects, resolving a job's code, data table migrations. `Full` flows or apps - /// require it, since both carry inline code. Previews also need `run`. + /// require it, since both carry inline code. Previews also need `run`. Also required to name + /// a Hub script or flow at run time (preset handlers excepted), see + /// [`crate::jobs::check_can_name_runnable`]. pub code: bool, pub flows: AuthorLevel, pub apps: AuthorLevel, @@ -757,7 +761,10 @@ async fn member_role(db: &DB, workspace_id: &str, username: &str) -> Result<Opti /// restricted, holds everything; a restricted caller holds its role's capabilities, or none if it /// has no membership (a guest, a removed member's job). `workspace_id` MUST be the route's. /// -/// Call it before opening an RLS transaction; see [`workspace_roles`]. +/// Queries nothing for a caller whose capabilities authentication filled in +/// ([`Authable::capabilities`]): a request's, unless reading its role failed then. Any other +/// caller has its role read from the pool, so for one call it before opening an RLS transaction; +/// see [`workspace_roles`]. pub async fn caller_capabilities<A: Authable + ?Sized>( db: &DB, workspace_id: &str, @@ -766,6 +773,9 @@ pub async fn caller_capabilities<A: Authable + ?Sized>( if authed.is_admin() || !authed.is_operator() { return Ok(RoleCapabilities::FULL); } + if let Some(caps) = authed.capabilities() { + return Ok(caps); + } match member_role(db, workspace_id, authed.username()).await? { Some(role) => role_capabilities_by_name(db, workspace_id, &role).await, None => Ok(RoleCapabilities::NONE), diff --git a/backend/windmill-common/src/ssrf.rs b/backend/windmill-common/src/ssrf.rs index c95137a8bb..b670a08d2c 100644 --- a/backend/windmill-common/src/ssrf.rs +++ b/backend/windmill-common/src/ssrf.rs @@ -216,7 +216,8 @@ fn allow_local_git_remotes() -> bool { } /// Who a git call is made for, which decides whether it may reach a host on a -/// private network. +/// private network, and whether the GitHub App installation serves it any +/// app-backed repository or only one an admin approved. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GitRemoteCaller { /// A workspace admin's request, or Windmill's own work (polling, webhook and diff --git a/backend/windmill-common/src/user_drafts.rs b/backend/windmill-common/src/user_drafts.rs index cd7d6e0959..a61a1cef57 100644 --- a/backend/windmill-common/src/user_drafts.rs +++ b/backend/windmill-common/src/user_drafts.rs @@ -661,6 +661,94 @@ pub async fn delete_own_draft_for_path( Ok(()) } +/// Copy drafts from `source` into its fork `target`, returning the `(kind, path)` of each row +/// copied. With `items = None` this is the fork-time clone: every row of `email` plus the legacy +/// NULL-email row. With `items`, only `email`'s own rows at those `(kind, path)` pairs. +/// +/// No authorization here. The caller MUST have checked that `target` is in `source`'s family, that +/// the credential behind `email` may act on `target`, and that it may write each copied path +/// there. Secret values are copied as encrypted, so the two workspaces must share a key. +/// +/// A row the target already holds is skipped and left out of the result: a conflict check earlier +/// in the transaction cannot see a save committed after it, so a caller that needs every row +/// copied compares the result with what it asked for. +/// `created_at` is preserved so the per-tab `last_sync` baseline the editor reads lines up with +/// the source's timeline — otherwise the first save from an open editor would trip the conflict +/// modal on every copied draft. +pub async fn copy_drafts_to_workspace( + conn: &mut sqlx::PgConnection, + source: &str, + target: &str, + email: &str, + items: Option<&[(UserDraftItemKind, String)]>, +) -> Result<Vec<(UserDraftItemKind, String)>> { + let (kinds, paths): (Option<Vec<&str>>, Option<Vec<&str>>) = match items { + Some(items) => ( + Some(items.iter().map(|(k, _)| k.as_str()).collect()), + Some(items.iter().map(|(_, p)| p.as_str()).collect()), + ), + None => (None, None), + }; + // A script/flow draft carries the principal in its value, and deploying it in the target + // would send a pair naming somebody who may not be a member there. Stripped rather than + // filtered: the address the draft still carries re-derives the target's own principal at + // deploy time, which is the more accurate answer of the two. + let rows = sqlx::query!( + // A script hash is content-addressed and shared between a workspace and its forks, so + // a script draft keeps its base (and `parent_hash`, both `ScriptHash`'s 16 hex digits, + // matched on the column so the lookup uses the key) when the target has that version, + // which a fork's clone does; one deployed in the source after the fork was made is not + // there, and a deploy naming it as parent would be refused. Flow and app ids are minted + // per workspace, so those drafts arrive with no base (staleness falls back to the + // timestamps), lineage field included, or the next autosave would re-derive the source id. + // + // `clean` is `strip_json_nul`'s parity rule in SQL, so a pre-sanitizer U+0000 escape + // cannot abort the copy on `to_jsonb` or arrive with its principal unstripped: escaped + // backslashes park on chr(1) (lossless, a `json` value's text cannot hold a raw control + // byte) so only a real NUL is removed, and chr(92) spells the backslash so no escape + // sequence reaches this source file. + r#"INSERT INTO draft (workspace_id, path, typ, value, created_at, email, base) + SELECT $2::text, path, typ, + to_json( + CASE WHEN typ IN ('script', 'flow') THEN clean - 'on_behalf_of' ELSE clean END + - CASE WHEN typ = 'flow' THEN 'version_id' + WHEN typ IN ('app', 'raw_app') THEN 'parent_version' + ELSE '' END + - CASE WHEN typ <> 'script' THEN '' + WHEN (clean->>'parent_hash' ~ '^[0-9a-f]{16}$') IS NOT TRUE THEN 'parent_hash' + WHEN EXISTS (SELECT 1 FROM script sc WHERE sc.workspace_id = $2::text + AND sc.hash = ('x' || (clean->>'parent_hash'))::bit(64)::bigint) + THEN '' ELSE 'parent_hash' END + ), + created_at, email, + CASE WHEN typ = 'script' AND base ~ '^[0-9a-f]{16}$' THEN + CASE WHEN EXISTS (SELECT 1 FROM script sc WHERE sc.workspace_id = $2::text + AND sc.hash = ('x' || base)::bit(64)::bigint) + THEN base END + END + FROM ( + SELECT d.path, d.typ, d.created_at, d.email, d.base, + replace(replace(replace(d.value::text, chr(92) || chr(92), chr(1)), chr(92) || 'u0000', ''), chr(1), chr(92) || chr(92))::jsonb AS clean + FROM draft d + WHERE d.workspace_id = $1 + AND CASE WHEN $4::text[] IS NULL THEN d.email = $3 OR d.email IS NULL + ELSE d.email = $3 + AND (d.typ::text, d.path) IN (SELECT * FROM unnest($4::text[], $5::text[])) + END + ) s + ON CONFLICT DO NOTHING + RETURNING typ AS "typ: UserDraftItemKind", path"#, + source, + target, + email, + kinds.as_deref() as Option<&[&str]>, + paths.as_deref() as Option<&[&str]>, + ) + .fetch_all(&mut *conn) + .await?; + Ok(rows.into_iter().map(|r| (r.typ, r.path)).collect()) +} + /// Carry every draft at `old_path` over to `new_path` when an item MOVES /// (rename or relocation). A draft is bound to its item by nothing but the path /// string, so without this a move detaches every draft on the item. No owner diff --git a/backend/windmill-common/src/users.rs b/backend/windmill-common/src/users.rs index 277a2632f8..8729b91732 100644 --- a/backend/windmill-common/src/users.rs +++ b/backend/windmill-common/src/users.rs @@ -109,6 +109,14 @@ pub fn username_to_permissioned_as(user: &str) -> String { format!("{}{}", PERMISSIONED_AS_USER_PREFIX, user) } +/// The principal a user's runnables carry, which a rename moves and offboarding hands over; +/// `None` for a legacy `group-*` username, which canonicalizes to the group it names: what runs +/// as that group outlives any one member. +pub fn username_to_own_permissioned_as(user: &str) -> Option<String> { + let principal = username_to_permissioned_as(user); + (!principal.starts_with(PERMISSIONED_AS_GROUP_PREFIX)).then_some(principal) +} + /// Borrowed key for zero-allocation cache lookups via `Equivalent<(String, String)>`. #[derive(Hash)] struct EmailCacheKey<'a>(&'a str, &'a str); diff --git a/backend/windmill-common/src/worker.rs b/backend/windmill-common/src/worker.rs index c1c1e9f582..9ac919fe6e 100644 --- a/backend/windmill-common/src/worker.rs +++ b/backend/windmill-common/src/worker.rs @@ -33,6 +33,7 @@ use crate::{ external_ip::UNKNOWN_IP, global_settings::CUSTOM_TAGS_SETTING, indexer::TantivyIndexerSettings, + runnable_ref::RunnableRef, server::Smtp, utils::{merge_nested_raw_values_to_array, merge_raw_values_to_array}, KillpillSender, DB, @@ -307,6 +308,25 @@ pub fn max_job_duration_secs(cloud_premium_workspace: bool) -> u64 { } } pub const MIN_PERIODIC_SCRIPT_INTERVAL_SECONDS: u64 = 60; + +/// `background_task_state` row the workspace fairness refresh writes [`WorkspaceFairnessState`] +/// to. Only pulls drive the refresh, so a row whose `updated_at` is old means no worker has +/// pulled lately, not that nothing is overloaded. +pub const WORKSPACE_FAIRNESS_STATE_NAME: &str = "workspace_fairness"; + +#[derive(Serialize, Deserialize, Default, Debug)] +pub struct WorkspaceFairnessState { + #[serde(default)] + pub overloaded: Vec<String>, + /// Admission probability for capped pulls in parts per 10_000. Absent in rows written + /// before it existed, which leaves the admission atomic at its default. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub admission_ppm: Option<u32>, + /// When each workspace in `overloaded` entered the list in its current episode of being + /// capped, carried across refreshes until it leaves. + #[serde(default)] + pub capped_since: HashMap<String, chrono::DateTime<chrono::Utc>>, +} /// Default for [`CONCURRENCY_KEY_MAX_QUEUED`]; also the value the setting loader restores when /// the setting is cleared or malformed. pub const CONCURRENCY_KEY_MAX_QUEUED_DEFAULT: u32 = 10_000; @@ -488,13 +508,15 @@ lazy_static::lazy_static! { native_mode: false, object_store_cache_config: Default::default(), paused: false, + fairness_reserve: false, }); pub static ref WORKER_PULL_QUERIES: arc_swap::ArcSwap<Vec<String>> = arc_swap::ArcSwap::from_pointee(vec![]); pub static ref WORKER_PULL_QUERIES_FAIRNESS: arc_swap::ArcSwap<Vec<String>> = arc_swap::ArcSwap::from_pointee(vec![]); pub static ref WORKER_SUSPENDED_PULL_QUERY: arc_swap::ArcSwap<String> = arc_swap::ArcSwap::from_pointee("".to_string()); + pub static ref WORKER_SUSPENDED_PULL_QUERY_FAIRNESS: arc_swap::ArcSwap<String> = arc_swap::ArcSwap::from_pointee("".to_string()); - // Workspace fairness (cloud-only). When enabled, a workspace whose footprint over the rolling + // Workspace fairness (Enterprise). When enabled, a workspace whose footprint over the rolling // `WORKSPACE_FAIRNESS_DURATION_SECS` window represents >= `WORKSPACE_FAIRNESS_MAX_PERCENT`% of // all worker activity gets excluded from the pull query, freeing slots for other workspaces. // The list of overloaded workspaces is computed cluster-wide via a single coordinated UPDATE @@ -654,6 +676,18 @@ pub static DEDICATED_WORKER_RELOAD: std::sync::LazyLock<tokio::sync::Notify> = std::sync::LazyLock::new(tokio::sync::Notify::new); pub static MIN_VERSION_IS_LATEST: AtomicBool = AtomicBool::new(false); +/// The server's error message, which callers match on to tell a retryable refusal (a volume +/// leased or being written by another worker) from a failure. +async fn agent_error_body(response: reqwest::Response) -> String { + response + .text() + .await + .unwrap_or_default() + .chars() + .take(1000) + .collect() +} + #[derive(Clone)] pub struct HttpClient { pub client: ClientWithMiddleware, @@ -692,11 +726,12 @@ impl HttpClient { if status.is_success() { Ok(response.json().await?) } else { - Err(anyhow::anyhow!(format!( - "HTTP agent request POST {} failed {}", + Err(anyhow::anyhow!( + "HTTP agent request POST {} failed {}: {}", url, - response.status() - ))) + status, + agent_error_body(response).await + )) } } @@ -712,11 +747,12 @@ impl HttpClient { if status.is_success() { Ok(response.json().await?) } else { - Err(anyhow::anyhow!(format!( - "HTTP agent request GET {} failed {}", + Err(anyhow::anyhow!( + "HTTP agent request GET {} failed {}: {}", url, - response.status() - ))) + status, + agent_error_body(response).await + )) } } @@ -852,29 +888,43 @@ fn format_pull_query(peek: String) -> String { // sync with `queue_suspended_v2` (migration 20260826202939): if it no longer matches, the // test silently reverts to a heap filter over every suspended row on every worker poll. pub fn make_suspended_pull_query(tags: &[String]) -> String { + suspended_pull_query(tags, "") +} + +/// [`make_suspended_pull_query`] leaving out the workspaces bound as `$2::text[]`. +pub fn make_suspended_pull_query_fairness(tags: &[String]) -> String { + suspended_pull_query(tags, "AND workspace_id <> ALL($2::text[])") +} + +fn suspended_pull_query(tags: &[String], extra_filter: &str) -> String { format_pull_query(format!( "SELECT id FROM v2_job_queue WHERE suspend_until IS NOT NULL AND (CASE WHEN suspend <= 0 THEN '-infinity'::timestamptz ELSE suspend_until END) <= now() AND tag IN ({}) + {extra_filter} ORDER BY priority DESC NULLS LAST, created_at FOR UPDATE SKIP LOCKED LIMIT 1", tags.iter().map(|x| format!("'{x}'")).join(", ") )) } -// pub async fn make_suspended + pub async fn store_suspended_pull_query(wc: &WorkerConfig) { // An empty tag list must clear the query: keeping the previous one would leave a reloaded // worker pulling suspended jobs for tags it no longer listens to. - let query = if wc.worker_tags.is_empty() { + let (query, fairness_query) = if wc.worker_tags.is_empty() { tracing::error!("Empty tags in worker tags, pulling no suspended jobs"); - String::new() + (String::new(), String::new()) } else { - make_suspended_pull_query(&wc.worker_tags) + ( + make_suspended_pull_query(&wc.worker_tags), + make_suspended_pull_query_fairness(&wc.worker_tags), + ) }; WORKER_SUSPENDED_PULL_QUERY.store(std::sync::Arc::new(query)); + WORKER_SUSPENDED_PULL_QUERY_FAIRNESS.store(std::sync::Arc::new(fairness_query)); } pub fn make_pull_query(tags: &[String]) -> String { @@ -2713,12 +2763,7 @@ pub async fn load_worker_config( "Invalid dedicated_worker format. Got {x}, expects <workspace_id>:<path>" )); } else { - let workspace = splitted[0]; - let script_path = splitted[1]; - Ok(WorkspacedPath { - workspace_id: workspace.to_string(), - path: script_path.to_string(), - }) + Ok(WorkspacedPath::dedicated(splitted[0], splitted[1])) } }) .transpose()?; @@ -2736,12 +2781,7 @@ pub async fn load_worker_config( "Invalid dedicated_workers format. Got {x}, expects <workspace_id>:<path>" )); } - let workspace = splitted[0]; - let script_path = splitted[1]; - Ok(WorkspacedPath { - workspace_id: workspace.to_string(), - path: script_path.to_string(), - }) + Ok(WorkspacedPath::dedicated(splitted[0], splitted[1])) }) .collect::<Result<Vec<_>, _>>() }) @@ -2919,6 +2959,17 @@ pub async fn load_worker_config( let native_mode = is_native_mode_from_env() || config.native_mode.unwrap_or(false); NATIVE_MODE_RESOLVED.store(native_mode, std::sync::atomic::Ordering::Relaxed); + // Fairness needs an Enterprise license, which a CE build (`private` included) never has, so + // no workspace would ever be overloaded and a reserve worker would idle forever. + let fairness_reserve = config.fairness_reserve.unwrap_or(false); + if fairness_reserve && !cfg!(feature = "enterprise") { + tracing::warn!( + "fairness_reserve is set on worker group {} but requires an Enterprise build, ignoring it", + *WORKER_GROUP + ); + } + let fairness_reserve = fairness_reserve && cfg!(feature = "enterprise"); + Ok(WorkerConfig { worker_tags, priority_tags_sorted, @@ -2942,6 +2993,7 @@ pub async fn load_worker_config( native_mode, object_store_cache_config: config.object_store_cache_config, paused: config.paused.unwrap_or(false), + fairness_reserve, }) } @@ -3103,6 +3155,26 @@ pub struct WorkspacedPath { pub path: String, } +impl WorkspacedPath { + /// A dedicated worker setting's `<path>`, a flow written `flow/<path>`, read the way job + /// resolution reads it: the result is the path its jobs' dedicated tag is built from. A path + /// that does not parse is kept as written: its tag matches no job, and refusing it would stop + /// the worker serving the other entries of its group. + pub fn dedicated(workspace_id: &str, path: &str) -> Self { + let runnable = if path.starts_with("flow/") { + RunnableRef::from_prefixed(path) + } else { + RunnableRef::from_path(path, false) + }; + let path = match runnable { + Ok(r) if r.is_flow() => format!("flow/{}", r.path()), + Ok(r) => r.path().to_string(), + Err(_) => path.to_string(), + }; + Self { workspace_id: workspace_id.to_string(), path } + } +} + #[derive(Serialize, Deserialize, Debug)] pub struct WorkerConfigOpt { pub worker_tags: Option<Vec<String>>, @@ -3122,6 +3194,7 @@ pub struct WorkerConfigOpt { pub object_store_cache_config: Option<serde_json::Value>, pub paused: Option<bool>, pub serves_dev_workspaces: Option<bool>, + pub fairness_reserve: Option<bool>, } impl Default for WorkerConfigOpt { @@ -3144,6 +3217,7 @@ impl Default for WorkerConfigOpt { object_store_cache_config: Default::default(), paused: Default::default(), serves_dev_workspaces: Default::default(), + fairness_reserve: Default::default(), } } } @@ -3171,12 +3245,15 @@ pub struct WorkerConfig { /// The group pulls no job from the queue: its workers finish what they hold, keep pinging /// and leave queued jobs for when it is resumed. pub paused: bool, + /// Pulls nothing while no workspace is overloaded, and otherwise only jobs of the workspaces + /// that are not. See "Reserve workers" in `windmill_queue::workspace_fairness`. + pub fairness_reserve: bool, } impl std::fmt::Debug for WorkerConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "WorkerConfig {{ worker_tags: {:?}, priority_tags_sorted: {:?}, dedicated_worker: {:?}, dedicated_workers: {:?}, init_bash: {:?}, periodic_script_bash: {:?}, periodic_script_interval_seconds: {:?}, cache_clear: {:?}, additional_python_paths: {:?}, pip_local_dependencies: {:?}, env_vars: {:?}, disable_job_proxy: {:?}, native_mode: {:?}, paused: {:?}, object_store_cache_config: {} }}", - self.worker_tags, self.priority_tags_sorted, self.dedicated_worker, self.dedicated_workers, self.init_bash, self.periodic_script_bash, self.periodic_script_interval_seconds, self.cache_clear, self.additional_python_paths, self.pip_local_dependencies, self.env_vars.iter().map(|(k, v)| format!("{}: {}{} ({} chars)", k, &v[..3.min(v.len())], "***", v.len())).collect::<Vec<String>>().join(", "), self.disable_job_proxy, self.native_mode, self.paused, + write!(f, "WorkerConfig {{ worker_tags: {:?}, priority_tags_sorted: {:?}, dedicated_worker: {:?}, dedicated_workers: {:?}, init_bash: {:?}, periodic_script_bash: {:?}, periodic_script_interval_seconds: {:?}, cache_clear: {:?}, additional_python_paths: {:?}, pip_local_dependencies: {:?}, env_vars: {:?}, disable_job_proxy: {:?}, native_mode: {:?}, paused: {:?}, fairness_reserve: {:?}, object_store_cache_config: {} }}", + self.worker_tags, self.priority_tags_sorted, self.dedicated_worker, self.dedicated_workers, self.init_bash, self.periodic_script_bash, self.periodic_script_interval_seconds, self.cache_clear, self.additional_python_paths, self.pip_local_dependencies, self.env_vars.iter().map(|(k, v)| format!("{}: {}{} ({} chars)", k, &v[..3.min(v.len())], "***", v.len())).collect::<Vec<String>>().join(", "), self.disable_job_proxy, self.native_mode, self.paused, self.fairness_reserve, // holds bucket credentials self.object_store_cache_config.as_ref().map(|_| "***").unwrap_or("None")) } @@ -3372,6 +3449,16 @@ mod tests { use super::*; use std::collections::HashMap; + #[test] + fn dedicated_path_is_read_like_a_job_path() { + let path = |p: &str| WorkspacedPath::dedicated("ws", p).path; + assert_eq!(path("/u/me/x"), "u/me/x"); + assert_eq!(path("flow//f/a/b"), "flow/f/a/b"); + assert_eq!(path("u/me/x"), "u/me/x"); + assert_eq!(path("//u/me/x"), "//u/me/x"); + assert_eq!(path("/f/dw/*"), "f/dw/*"); + } + #[test] fn whitelist_env_secret_heuristic() { let cases = [ @@ -3941,7 +4028,10 @@ mod tests { #[test] fn dedicated_worker_patterns_are_script_folders() { assert_eq!(dedicated_worker_pattern_prefix("f/dw/*"), Some("f/dw/")); - assert_eq!(dedicated_worker_pattern_prefix("u/alice/*"), Some("u/alice/")); + assert_eq!( + dedicated_worker_pattern_prefix("u/alice/*"), + Some("u/alice/") + ); assert_eq!(dedicated_worker_pattern_prefix("f/dw/script"), None); assert_eq!(dedicated_worker_pattern_prefix("f/dw*"), None); assert_eq!(dedicated_worker_pattern_prefix("/*"), None); diff --git a/backend/windmill-common/src/workspaces.rs b/backend/windmill-common/src/workspaces.rs index 85d0290a87..2c43456896 100644 --- a/backend/windmill-common/src/workspaces.rs +++ b/backend/windmill-common/src/workspaces.rs @@ -206,7 +206,7 @@ pub enum ObjectType { DatatableMigration, } -pub const LATEST_GIT_SYNC_SCRIPT_PATH: &str = "hub/30174/sync-script-to-git-repo-windmill"; +pub const LATEST_GIT_SYNC_SCRIPT_PATH: &str = "hub/30453/sync-script-to-git-repo-windmill"; /// Hub script that applies a repository's state back into a workspace /// (the repo → Windmill / "pull" direction). Same script the UI runs from @@ -214,12 +214,12 @@ pub const LATEST_GIT_SYNC_SCRIPT_PATH: &str = "hub/30174/sync-script-to-git-repo /// ignores the slug, so the slug is kept free of characters that would be /// percent-encoded into the run URL (a `:` becomes `%3A`, which some hardened /// reverse proxies reject as double-encoding when the client re-encodes it). -pub const GIT_SYNC_PULL_SCRIPT_PATH: &str = "hub/30172/git-sync-init-repository-windmill"; +pub const GIT_SYNC_PULL_SCRIPT_PATH: &str = "hub/30451/git-sync-init-repository-windmill"; /// Hub script that reviews a pull request with the workspace's AI (`ai_review_prs`): clones /// the base branch, fetches the pull request's head and runs `wmill review --json` from the /// `windmill-cli` it pins. The server posts what it returns. -pub const GIT_SYNC_REVIEW_SCRIPT_PATH: &str = "hub/30173/git-sync-review-pull-request-windmill"; +pub const GIT_SYNC_REVIEW_SCRIPT_PATH: &str = "hub/30452/git-sync-review-pull-request-windmill"; /// Prefix used to identify fork workspaces. A workspace whose id starts with this string is a /// fork of another workspace. @@ -1101,6 +1101,18 @@ pub async fn count_paid_seats(db: &crate::DB, w_id: &str) -> Result<i64> { Ok(billable_seats(db, w_id).await?.seats) } +/// Whether a workspace may use what Windmill Cloud reserves for paid plans (public apps, HTML +/// and redirect job responses). Resolved through the fork/dev root; always true off the cloud. +/// Reads billing state on the unrestricted pool: callers must already have authorized the +/// request for `w_id`. +pub async fn paid_features_allowed(_db: &crate::DB, _w_id: &str) -> Result<bool> { + #[cfg(feature = "cloud")] + if *crate::worker::CLOUD_HOSTED { + return Ok(get_team_plan_status(_db, _w_id).await?.premium); + } + Ok(true) +} + #[cfg(feature = "cloud")] pub async fn get_team_plan_status(_db: &crate::DB, _w_id: &str) -> Result<TeamPlanStatus> { // A fork/dev workspace draws its plan from the root (billing) workspace. Resolve to the root and @@ -3994,6 +4006,7 @@ mod tests { folders: &folders, scopes: &scopes, token_prefix: &token_prefix, + capabilities: Some(crate::roles::RoleCapabilities::FULL), }; assert!(can_use_datatable_role(&tenants(&["u/alice"]), &authed)); @@ -4032,6 +4045,7 @@ mod tests { folders: &folders, scopes: &scopes, token_prefix: &token_prefix, + capabilities: Some(crate::roles::RoleCapabilities::FULL), }; assert!(!can_use_datatable_role(&tenants(&["*"]), &admin)); assert!(!can_use_datatable_role(&tenants(&["u/alice"]), &admin)); diff --git a/backend/windmill-dep-map/src/ci_tests.rs b/backend/windmill-dep-map/src/ci_tests.rs index 8f56111b35..951417a50d 100644 --- a/backend/windmill-dep-map/src/ci_tests.rs +++ b/backend/windmill-dep-map/src/ci_tests.rs @@ -2,12 +2,179 @@ #[allow(unused)] pub use crate::ci_tests_ee::*; -#[cfg(not(feature = "private"))] -use uuid::Uuid; +use std::collections::BTreeSet; +use std::time::Duration; -#[cfg(not(feature = "private"))] +use uuid::Uuid; use windmill_common::error; +use crate::scoped_dependency_map::ScopedDependencyMap; + +/// `skip_ci_tests` on a deploy endpoint. A caller deploying several items in a row sets it +/// and queues the CI tests once the whole batch has landed (`trigger_ci_tests_for_batch`): a +/// test run between two of its deploys resolves imports against a half-deployed workspace. +#[derive(serde::Deserialize, Default, Clone, Copy)] +pub struct SkipCiTestsQuery { + #[serde(default)] + pub skip_ci_tests: bool, +} + +/// How long after a deploy that brings its own lock the scripts importing it are relocked: +/// that deploy queues no dependency job, so until then nothing shows the relock is coming. +pub const LOCKED_DEPLOY_RELOCK_DELAY: Duration = Duration::from_secs(10); + +#[derive(serde::Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct CiTestBatchItem { + pub kind: String, + pub path: String, +} + +#[derive(serde::Serialize, Default)] +pub struct CiTestBatchOutcome { + /// Paths with a dependency job still queued or running. When non-empty and the caller + /// did not ask to ignore it, nothing was queued. + pub pending: Vec<String>, + pub job_ids: Vec<Uuid>, +} + +/// Queue the CI tests of a batch deployed with `skip_ci_tests`, once nothing those tests read +/// is still being locked. The relocks a deployed script causes in the scripts importing it +/// carry the flag too, so those importers' tests are part of the batch. +/// +/// Checks no permission and queues the tests as `email`/`username`: the caller must have +/// verified that this identity may deploy each of `items`, as a deploy would. +pub async fn trigger_ci_tests_for_batch( + db: &sqlx::Pool<sqlx::Postgres>, + w_id: &str, + items: Vec<CiTestBatchItem>, + ignore_pending: bool, + email: &str, + username: &str, +) -> error::Result<CiTestBatchOutcome> { + let mut items: BTreeSet<CiTestBatchItem> = items + .into_iter() + .filter(|i| matches!(i.kind.as_str(), "script" | "flow" | "resource")) + .collect(); + + let mut frontier: Vec<String> = items + .iter() + .filter(|i| i.kind == "script") + .map(|i| i.path.clone()) + .collect(); + let mut relocks: Vec<(String, String)> = vec![]; + while let Some(path) = frontier.pop() { + for d in ScopedDependencyMap::get_dependents(&path, w_id, db).await? { + if d.importer_kind != "script" { + continue; + } + relocks.push((path.clone(), d.importer_path.clone())); + if items.insert(CiTestBatchItem { + kind: "script".to_string(), + path: d.importer_path.clone(), + }) { + frontier.push(d.importer_path); + } + } + } + + let refs = sqlx::query!( + "SELECT test_script_path, tested_item_path, tested_item_kind, has_wildcard AS \"has_wildcard!\" \ + FROM ci_test_reference WHERE workspace_id = $1", + w_id + ) + .fetch_all(db) + .await?; + // What a test run reads: the tested item, the test script and everything it imports. + // Any of them still being locked would have the test run on its previous lock. + let mut watched: BTreeSet<String> = BTreeSet::new(); + let mut visited: BTreeSet<String> = BTreeSet::new(); + let mut to_visit: Vec<String> = vec![]; + for r in refs { + let mut tested = items + .iter() + .filter(|i| { + i.kind == r.tested_item_kind + && if r.has_wildcard { + windmill_common::schema::ci_test_path_matches(&i.path, &r.tested_item_path) + } else { + i.path == r.tested_item_path + } + }) + .peekable(); + if tested.peek().is_none() { + continue; + } + watched.extend(tested.map(|i| i.path.clone())); + if visited.insert(r.test_script_path.clone()) { + to_visit.push(r.test_script_path); + } + } + // Waiting on the batch's locks is only worth it when there is a test to run after them. + if to_visit.is_empty() { + return Ok(CiTestBatchOutcome::default()); + } + while let Some(path) = to_visit.pop() { + let imported = sqlx::query_scalar!( + "SELECT DISTINCT imported_path FROM dependency_map \ + WHERE workspace_id = $1 AND importer_path = $2 AND importer_kind = 'script'", + w_id, + &path + ) + .fetch_all(db) + .await?; + for p in imported { + if visited.insert(p.clone()) { + to_visit.push(p); + } + } + } + watched.extend(visited); + + let watched: Vec<String> = watched.into_iter().collect(); + let mut pending = sqlx::query_scalar!( + "SELECT DISTINCT j.runnable_path AS \"path!\" FROM v2_job_queue q + JOIN v2_job j ON j.id = q.id + WHERE q.workspace_id = $1 + AND j.kind IN ('dependencies', 'flowdependencies') + AND j.runnable_path = ANY($2)", + w_id, + &watched + ) + .fetch_all(db) + .await?; + // A relock still waiting out its delay is in no queue yet: count its source as pending. + let relocking: Vec<String> = relocks + .into_iter() + .filter(|(_, importer)| watched.contains(importer)) + .map(|(source, _)| source) + .collect(); + let recently_deployed = sqlx::query_scalar!( + "SELECT DISTINCT path FROM script WHERE workspace_id = $1 AND path = ANY($2) \ + AND created_at > now() - make_interval(secs => $3)", + w_id, + &relocking, + (LOCKED_DEPLOY_RELOCK_DELAY + Duration::from_secs(5)).as_secs_f64() + ) + .fetch_all(db) + .await?; + for path in recently_deployed { + if !pending.contains(&path) { + pending.push(path); + } + } + if !pending.is_empty() && !ignore_pending { + return Ok(CiTestBatchOutcome { pending, job_ids: vec![] }); + } + + let mut job_ids = vec![]; + for item in items { + job_ids.extend( + trigger_ci_tests_for_item(db, w_id, &item.path, &item.kind, email, username).await?, + ); + } + Ok(CiTestBatchOutcome { pending, job_ids }) +} + #[cfg(not(feature = "private"))] pub async fn trigger_ci_tests_for_item( _db: &sqlx::Pool<sqlx::Postgres>, diff --git a/backend/windmill-dep-map/src/lib.rs b/backend/windmill-dep-map/src/lib.rs index 1d47056cf9..3e00a72f9c 100644 --- a/backend/windmill-dep-map/src/lib.rs +++ b/backend/windmill-dep-map/src/lib.rs @@ -207,6 +207,9 @@ pub async fn process_relative_imports( permissioned_as, db, already_visited, + args.and_then(|x| x.get("skip_ci_tests")) + .and_then(|v| serde_json::from_str::<bool>(v.get()).ok()) + .unwrap_or(false), )), ) .warn_after_seconds(10) diff --git a/backend/windmill-dep-map/src/trigger_dependents.rs b/backend/windmill-dep-map/src/trigger_dependents.rs index c1ab87e682..17248c6aa0 100644 --- a/backend/windmill-dep-map/src/trigger_dependents.rs +++ b/backend/windmill-dep-map/src/trigger_dependents.rs @@ -33,6 +33,7 @@ pub async fn trigger_dependents_to_recompute_dependencies( permissioned_as: &str, db: &sqlx::Pool<sqlx::Postgres>, already_visited: Vec<String>, + skip_ci_tests: bool, ) -> error::Result<()> { tracing::debug!( "Triggering dependents to recompute dependencies: {}", @@ -64,6 +65,9 @@ pub async fn trigger_dependents_to_recompute_dependencies( "triggered_by_relative_import".to_string(), to_raw_value(&true), ); + if skip_ci_tests { + args.insert("skip_ci_tests".to_string(), to_raw_value(&true)); + } let mut debouncing_settings = DebouncingSettings { debounce_key: Some(format!("{w_id}:{importer_path}:{importer_kind}:dependency")), diff --git a/backend/windmill-dep-map/src/workspace_dependencies.rs b/backend/windmill-dep-map/src/workspace_dependencies.rs index f4dd404133..693d777ac3 100644 --- a/backend/windmill-dep-map/src/workspace_dependencies.rs +++ b/backend/windmill-dep-map/src/workspace_dependencies.rs @@ -178,6 +178,7 @@ pub async fn trigger_dependents_to_recompute_dependencies_in_the_background( permissioned_as.as_str(), &db, vec![], + false, ) .await { diff --git a/backend/windmill-jseval/src/lib.rs b/backend/windmill-jseval/src/lib.rs index 55c82e1d13..9b87b28cbd 100644 --- a/backend/windmill-jseval/src/lib.rs +++ b/backend/windmill-jseval/src/lib.rs @@ -253,6 +253,32 @@ pub async fn eval_timeout_quickjs( authed_client: Option<&AuthedClient>, by_id: Option<&IdContext>, ctx: Option<Vec<(String, String)>>, +) -> anyhow::Result<Box<RawValue>> { + eval_timeout_quickjs_within( + std::time::Duration::from_millis(EVAL_TIMEOUT_MS), + expr, + transform_context, + flow_input, + flow_env, + authed_client, + by_id, + ctx, + ) + .await +} + +/// [`eval_timeout_quickjs`] with its own time limit. QuickJS is interrupted at the limit, so a +/// script that never returns does not keep its blocking thread busy after the caller gave up. +#[cfg(feature = "quickjs")] +pub async fn eval_timeout_quickjs_within( + timeout: std::time::Duration, + expr: String, + transform_context: HashMap<String, Arc<Box<RawValue>>>, + flow_input: Option<mappable_rc::Marc<HashMap<String, Box<RawValue>>>>, + flow_env: Option<&HashMap<String, Box<RawValue>>>, + authed_client: Option<&AuthedClient>, + by_id: Option<&IdContext>, + ctx: Option<Vec<(String, String)>>, ) -> anyhow::Result<Box<RawValue>> { let expr = expr.trim().to_string(); @@ -315,8 +341,9 @@ pub async fn eval_timeout_quickjs( // and producing spurious "DispatchGone" / "runtime dropped the dispatch // task" errors on subsequent requests from the main runtime. let handle = tokio::runtime::Handle::current(); + let deadline = std::time::Instant::now() + timeout; tokio::time::timeout( - std::time::Duration::from_millis(EVAL_TIMEOUT_MS), + timeout, tokio::task::spawn_blocking(move || { handle.block_on(async move { eval_quickjs_inner( @@ -329,6 +356,7 @@ pub async fn eval_timeout_quickjs( ctx, context_keys, memory_limit, + Some(deadline), ) .await }) @@ -337,7 +365,8 @@ pub async fn eval_timeout_quickjs( .await .map_err(|_| { anyhow::anyhow!( - "The expression evaluation `{expr}` took too long to execute (>{EVAL_TIMEOUT_MS}ms)" + "The expression evaluation `{expr}` took too long to execute (>{}ms)", + timeout.as_millis() ) })?? } @@ -445,9 +474,17 @@ async fn eval_quickjs_inner( extra_ctx: Option<Vec<(String, String)>>, context_keys: Vec<String>, memory_limit: usize, + deadline: Option<std::time::Instant>, ) -> anyhow::Result<Box<RawValue>> { let runtime = AsyncRuntime::new()?; runtime.set_memory_limit(memory_limit).await; + if let Some(deadline) = deadline { + runtime + .set_interrupt_handler(Some(Box::new(move || { + std::time::Instant::now() >= deadline + }))) + .await; + } let context = AsyncContext::full(&runtime).await?; // Create shared state for async ops if we have a client @@ -469,7 +506,7 @@ async fn eval_quickjs_inner( format!("__loadResults({})", serde_json::to_string(&step_ids)?) }; - async_with!(context => |ctx| { + let result: anyhow::Result<Box<RawValue>> = async_with!(context => |ctx| { let globals = ctx.globals(); // Set up context variables @@ -584,15 +621,29 @@ async fn eval_quickjs_inner( // Evaluate the expression (returns a Promise that resolves to a JSON string) let promise: rquickjs::Promise = ctx.eval(code).catch(&ctx).map_err(|e| map_quickjs_error(e, memory_limit, Some("QUICKJS_MEMORY_LIMIT_MB")))?; - // Await the promise - let result: Value = promise.into_future().await.catch(&ctx).map_err(|e| map_quickjs_error(e, memory_limit, Some("QUICKJS_MEMORY_LIMIT_MB")))?; + // An interrupted job never settles its promise, so the deadline also bounds the wait. + let settled = promise.into_future::<Value>(); + let settled = match deadline { + Some(deadline) => tokio::time::timeout_at(deadline.into(), settled) + .await + .map_err(|_| anyhow::anyhow!("The expression evaluation `{expr}` took too long to execute"))?, + None => settled.await, + }; + let result: Value = settled.catch(&ctx).map_err(|e| map_quickjs_error(e, memory_limit, Some("QUICKJS_MEMORY_LIMIT_MB")))?; let json_str = String::from_js(&ctx, result) .unwrap_or_else(|_| "null".to_string()); Ok(unsafe_raw(json_str)) }) - .await + .await; + // Whatever the interrupt surfaced as, report it the way callers recognize (and retry) a timeout. + match result { + Err(_) if deadline.is_some_and(|d| std::time::Instant::now() >= d) => Err(anyhow::anyhow!( + "The expression evaluation `{expr}` took too long to execute" + )), + result => result, + } } #[cfg(feature = "quickjs")] @@ -1053,6 +1104,20 @@ pub async fn eval_timeout_quickjs( anyhow::bail!("JavaScript expression evaluation requires the `quickjs` feature. Enable it with: cargo build --features quickjs") } +#[cfg(not(feature = "quickjs"))] +pub async fn eval_timeout_quickjs_within( + _timeout: std::time::Duration, + _expr: String, + _transform_context: HashMap<String, Arc<Box<RawValue>>>, + _flow_input: Option<mappable_rc::Marc<HashMap<String, Box<RawValue>>>>, + _flow_env: Option<&HashMap<String, Box<RawValue>>>, + _authed_client: Option<&windmill_common::client::AuthedClient>, + _by_id: Option<&IdContext>, + _ctx: Option<Vec<(String, String)>>, +) -> anyhow::Result<Box<RawValue>> { + anyhow::bail!("JavaScript expression evaluation requires the `quickjs` feature. Enable it with: cargo build --features quickjs") +} + #[cfg(not(feature = "quickjs"))] pub async fn eval_simple_js( _expr: String, @@ -2987,6 +3052,7 @@ mod tests { None, Vec::new(), 4 * 1024 * 1024, + None, ) .await .expect_err("expected OOM to fail") @@ -3061,6 +3127,28 @@ mod tests { } } + #[tokio::test] + async fn test_eval_stops_at_its_deadline() { + // Without the interrupt the script never returns, and a caller's timeout only stops + // waiting for it. + let deadline = std::time::Instant::now() + std::time::Duration::from_millis(200); + let err = eval_quickjs_inner( + "(() => { while (true) {} })()", + HashMap::new(), + None, + None, + None, + None, + None, + Vec::new(), + 4 * 1024 * 1024, + Some(deadline), + ) + .await; + let err = err.expect_err("an endless script must be interrupted").to_string(); + assert!(err.contains("took too long"), "unexpected error: {err}"); + } + #[tokio::test] async fn test_eval_issue_payload_succeeds_with_raised_cap() { // The exact #8073 payload exceeds the conservative default but succeeds @@ -3077,6 +3165,7 @@ mod tests { None, Vec::new(), 256 * 1024 * 1024, + None, ) .await .expect("issue payload should evaluate once the cap is raised"); diff --git a/backend/windmill-mcp/src/server/backend.rs b/backend/windmill-mcp/src/server/backend.rs index 98831279d5..1dd746a2b7 100644 --- a/backend/windmill-mcp/src/server/backend.rs +++ b/backend/windmill-mcp/src/server/backend.rs @@ -17,6 +17,17 @@ use crate::server::endpoints::EndpointTool; /// Result type for backend operations using rmcp's ErrorData directly pub type BackendResult<T> = Result<T, ErrorData>; +/// How a script or flow run by a tool ended. +pub enum RunOutcome { + Success(Value), + /// The job ran and failed. `result` is the job's result, its error object included. + Failed { + job_id: String, + run_url: String, + result: Value, + }, +} + /// What a v2 token may do: read, read and run deployed scripts, flows and agents /// (`mcp:read_run`), or everything its owner can. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -108,6 +119,10 @@ pub trait McpBackend: Send + Sync + Clone + 'static { ) { } + /// Whether the caller's role may start runs in the workspace: the same check + /// `run_script` and `run_flow` refuse on, so the listing offers no tool that always fails. + async fn can_run(&self, auth: &Self::Auth, workspace_id: &str) -> BackendResult<bool>; + // ───────────────────────────────────────────────────────────────── // Listing Operations // ───────────────────────────────────────────────────────────────── @@ -202,7 +217,7 @@ pub trait McpBackend: Send + Sync + Clone + 'static { path: &str, args: Value, request: &McpRequest<'_>, - ) -> BackendResult<Value>; + ) -> BackendResult<RunOutcome>; /// Run a flow and wait for result async fn run_flow( @@ -212,7 +227,7 @@ pub trait McpBackend: Send + Sync + Clone + 'static { path: &str, args: Value, request: &McpRequest<'_>, - ) -> BackendResult<Value>; + ) -> BackendResult<RunOutcome>; /// Call an endpoint tool (generated API endpoint) async fn call_endpoint( diff --git a/backend/windmill-mcp/src/server/mod.rs b/backend/windmill-mcp/src/server/mod.rs index 545812a411..69ce01be4f 100644 --- a/backend/windmill-mcp/src/server/mod.rs +++ b/backend/windmill-mcp/src/server/mod.rs @@ -14,7 +14,9 @@ pub mod tools; // Re-export main types pub use crate::common::types::{McpToken, MultiWorkspaceMcp, NoEndpointTools, WorkspaceInfo}; -pub use backend::{BackendResult, McpAuth, McpBackend, McpRequest, PathFilter, SessionAccess}; +pub use backend::{ + BackendResult, McpAuth, McpBackend, McpRequest, PathFilter, RunOutcome, SessionAccess, +}; pub use endpoints::{ endpoint_tool_to_mcp_tool, endpoint_tool_to_mcp_tool_multi, is_endpoint_read_only, list_workspaces_tool, non_empty_body_fields, with_workspace_id_arg, EndpointTool, diff --git a/backend/windmill-mcp/src/server/runner.rs b/backend/windmill-mcp/src/server/runner.rs index 6e18f36c7b..6af8eebc1b 100644 --- a/backend/windmill-mcp/src/server/runner.rs +++ b/backend/windmill-mcp/src/server/runner.rs @@ -14,7 +14,7 @@ use crate::common::types::{ McpToken, MultiWorkspaceMcp, NoEndpointTools, ResourceInfo, SchemaType, ToolableItem, WorkspaceId, }; -use crate::server::backend::{McpAuth, McpBackend, McpRequest, PathFilter}; +use crate::server::backend::{McpAuth, McpBackend, McpRequest, PathFilter, RunOutcome}; use crate::server::endpoints::{ endpoint_tool_to_mcp_tool, endpoint_tool_to_mcp_tool_multi, list_workspaces_tool, EndpointTool, }; @@ -87,6 +87,55 @@ pub(super) fn truncate_tool_result(text: String) -> String { truncated } +const MAX_PARTIAL_RESULT_BYTES: usize = 2_000; + +/// A failed run as a tool execution error: the error's name and message, the run to open, and a +/// short excerpt of whatever else the result holds. The stack trace is left to the run's page. +fn failed_run_result( + tool_type: &str, + job_id: &str, + run_url: &str, + mut result: Value, +) -> CallToolResult { + let mut headline = None; + if let Some(obj) = result.as_object_mut() { + if let Some(Value::Object(error)) = obj.get_mut("error") { + let name = error.remove("name"); + let message = error.remove("message"); + error.remove("stack"); + if error.get("job_id").and_then(Value::as_str) == Some(job_id) { + error.remove("job_id"); + } + let [name, message] = [&name, &message].map(|v| v.as_ref().and_then(Value::as_str)); + headline = match (name, message) { + (Some(n), Some(m)) => Some(format!("{n}: {m}")), + (n, m) => n.or(m).map(str::to_string), + }; + if error.is_empty() { + obj.remove("error"); + } + } + } + // The run id comes first so that truncating a huge message never cuts it off. + let mut text = format!("The {tool_type} failed. Run id: {job_id} ({run_url})"); + if let Some(h) = headline { + text.push_str(&format!("\n{h}")); + } + if !matches!(&result, Value::Object(o) if o.is_empty()) && !result.is_null() { + let mut rest = result.to_string(); + if rest.len() > MAX_PARTIAL_RESULT_BYTES { + let mut end = MAX_PARTIAL_RESULT_BYTES; + while !rest.is_char_boundary(end) { + end -= 1; + } + rest.truncate(end); + rest.push_str("… [truncated, the full result is on the run]"); + } + text.push_str(&format!("\nPartial result: {rest}")); + } + CallToolResult::error(vec![ContentBlock::text(truncate_tool_result(text))]) +} + /// MCP Server Runner - generic over the backend implementation /// /// This struct implements the MCP ServerHandler trait and uses a McpBackend @@ -758,10 +807,10 @@ impl<B: McpBackend> Runner<B> { let mut tools = Vec::new(); - // Read-only tokens cannot run scripts/flows/hub-scripts (running is a - // mutating action), so skip the script/flow/hub/resource fetches - // entirely — they would only be discarded below. - if !read_only { + // Read-only tokens and roles without the run capability cannot run + // scripts/flows/hub-scripts, so skip the script/flow/hub/resource fetches. + let can_run = !read_only && self.backend.can_run(auth, workspace_id).await?; + if can_run { // For granular tokens, push the scope patterns into the SQL query so // in-scope items survive the fetch cap (see `PathFilter`). The Rust // filter below still runs as a defense-in-depth check. Non-granular @@ -878,10 +927,9 @@ impl<B: McpBackend> Runner<B> { } } - // Add endpoint tools from the generated MCP tools, filtered by scope. - // Uses the same run-by-path-aware gate as multi-workspace mode so a - // granular token only sees runScriptByPath / runFlowByPath when it can - // actually run scripts / flows. + // Add endpoint tools from the generated MCP tools, filtered by scope with + // the same run-by-path-aware gate as multi-workspace mode. The run endpoints + // are also left out for a role the jobs router's run gate would refuse. let endpoint_tools = self.backend.all_endpoint_tools(); for endpoint_tool in endpoint_tools { if !endpoint_tool_in_scope(scope_config, &endpoint_tool) { @@ -890,6 +938,14 @@ impl<B: McpBackend> Runner<B> { if read_only && !crate::server::is_endpoint_read_only(&endpoint_tool) { continue; } + if !can_run + && matches!( + endpoint_tool.name.as_ref(), + "runScriptByPath" | "runFlowByPath" | "runScriptPreviewAndWaitResult" + ) + { + continue; + } tools.push(endpoint_tool_to_mcp_tool(&endpoint_tool)); } @@ -1098,11 +1154,16 @@ impl<B: McpBackend> Runner<B> { }; match result { - Ok(value) => Ok(CallToolResult::success(vec![ContentBlock::text( - truncate_tool_result( - serde_json::to_string_pretty(&value).unwrap_or_else(|_| "{}".to_string()), - ), - )])), + Ok(RunOutcome::Success(value)) => { + Ok(CallToolResult::success(vec![ContentBlock::text( + truncate_tool_result( + serde_json::to_string_pretty(&value).unwrap_or_else(|_| "{}".to_string()), + ), + )])) + } + Ok(RunOutcome::Failed { job_id, run_url, result }) => { + Ok(failed_run_result(tool_type, &job_id, &run_url, result)) + } Err(e) => Err(ErrorData::internal_error( format!("Failed to run {}: {}", tool_type, e.message), None, @@ -1606,4 +1667,28 @@ mod tests { ) .is_ok()); } + + #[test] + fn failed_run_is_a_tool_error_without_the_stack() { + let result = json!({ "error": { + "name": "Error", + "message": "boom", + "stack": "Error: boom\n at main (/tmp/main.ts:2:9)", + "step_id": "a", + "job_id": "0192-id", + }}); + let res = failed_run_result("script", "0192-id", "http://wm/run/0192-id", result); + assert_eq!(res.is_error, Some(true)); + let text = res.content[0].as_text().unwrap().text.clone(); + assert!(text.contains("Error: boom"), "{text}"); + assert!(text.contains("0192-id"), "{text}"); + assert!(text.contains(r#"{"error":{"step_id":"a"}}"#), "{text}"); + assert!(!text.contains("main.ts"), "{text}"); + + let huge = json!({ "error": { "name": "Error", "message": "x".repeat(200_000) } }); + let res = failed_run_result("script", "0192-id", "http://wm/run/0192-id", huge); + let text = &res.content[0].as_text().unwrap().text; + assert!(text.len() < MAX_TOOL_RESULT_BYTES + 100, "{}", text.len()); + assert!(text.contains("0192-id")); + } } diff --git a/backend/windmill-mcp/src/server/session.rs b/backend/windmill-mcp/src/server/session.rs index 25d9da8dea..7c4a7d68e7 100644 --- a/backend/windmill-mcp/src/server/session.rs +++ b/backend/windmill-mcp/src/server/session.rs @@ -284,9 +284,23 @@ impl<B: McpBackend> ServerHandler for SessionRunner<B> { if let McpMode::Multi(_) = caller.mode { tools.push(get_workspace_context_tool()); } + let mut access = access(&caller.auth, &caller.scope); + // A bound token's one workspace decides its toolset as it decides its instructions: + // a role there that cannot run gets the read-only tools. + if let McpMode::Single(bound) = &caller.mode { + if access != SessionAccess::ReadOnly + && !self + .backend + .can_run(&caller.auth, bound) + .await + .unwrap_or(true) + { + access = SessionAccess::ReadOnly; + } + } tools.extend( self.backend - .session_tools(access(&caller.auth, &caller.scope)) + .session_tools(access) .into_iter() .map(with_workspace_id_arg), ); diff --git a/backend/windmill-oauth/src/lib.rs b/backend/windmill-oauth/src/lib.rs index ac53ddeaf8..e986fffa7d 100644 --- a/backend/windmill-oauth/src/lib.rs +++ b/backend/windmill-oauth/src/lib.rs @@ -251,6 +251,109 @@ pub fn resolve_registry_config( None } +/// Check the instance `oauths` setting before it is written. Each problem names its +/// entry. Without this, a bad entry is dropped when clients are built, or fails the +/// parse of the whole map so that every provider disappears, and only a log line says so. +/// Entries identical to the stored `previous` value are skipped: one saved before this +/// check existed must not block a save that does not touch it. +pub fn validate_oauths_setting( + value: &serde_json::Value, + previous: Option<&serde_json::Value>, + connect_configs_json: &str, +) -> Result<(), String> { + if value.is_null() { + return Ok(()); + } + let serde_json::Value::Object(entries) = value else { + return Err("the OAuth setting must be an object keyed by client name".to_string()); + }; + let registry = serde_json::from_str::<HashMap<String, OAuthConfig>>(connect_configs_json) + .map_err(|e| format!("parsing oauth_connect.json: {e}"))?; + let mut errors = vec![]; + for (name, raw) in entries { + if previous.and_then(|p| p.get(name)) == Some(raw) { + continue; + } + if let Err(e) = validate_oauth_entry(name, raw, ®istry) { + errors.push(format!("{name}: {e}")); + } + } + if errors.is_empty() { + Ok(()) + } else { + Err(errors.join("; ")) + } +} + +fn validate_oauth_entry( + name: &str, + raw: &serde_json::Value, + registry: &HashMap<String, OAuthConfig>, +) -> Result<(), String> { + let entry: OAuthClient = serde_json::from_value(raw.clone()).map_err(|e| e.to_string())?; + for gt in &entry.grant_types { + if gt != "authorization_code" && gt != "client_credentials" { + return Err(format!("unknown grant type '{gt}'")); + } + } + for cfg in [&entry.connect_config, &entry.login_config] + .into_iter() + .flatten() + { + for url in [&cfg.auth_url, &cfg.token_url] { + if !url.is_empty() { + Url::parse(url).map_err(|e| format!("invalid URL '{url}': {e}"))?; + } + } + } + let registry_entry = resolve_registry_config(registry, name); + // The settings page builds a per-instance provider's URLs from the instance name it + // stores in extra_params, even an empty one, which leaves them on no host. An entry + // without that key had its URLs written out by hand. + if let Some(tmpl) = registry_entry + .as_ref() + .and_then(|r| r.connect_config_template.as_ref()) + { + let key = tmpl.extra_params_key.as_deref().unwrap_or("instance"); + let instance = entry + .connect_config + .as_ref() + .and_then(|c| c.extra_params.as_ref()) + .and_then(|p| p.get(key)); + let explicit_urls = entry + .connect_config + .as_ref() + .is_some_and(|c| !c.token_url.is_empty() && !c.token_url.contains('{')); + // Teams keeps its tenant at the top level and the backend builds its URLs from it. + let has_tenant = entry.tenant.as_deref().is_some_and(|t| !t.is_empty()); + let missing = !has_tenant + && match instance { + Some(v) => v.is_empty(), + None => !explicit_urls, + }; + if !entry.id.is_empty() && missing { + return Err(format!("{} is required", tmpl.label)); + } + } + if !entry.grant_types.iter().any(|g| g == "client_credentials") { + return Ok(()); + } + match registry_entry { + Some(reg) if !reg.grant_types.iter().any(|g| g == "client_credentials") => { + Err("this provider does not support the client credentials grant".to_string()) + } + Some(_) => Ok(()), + None if entry + .connect_config + .as_ref() + .is_none_or(|c| c.token_url.is_empty()) => + { + Err("client credentials needs a token URL".to_string()) + } + None => Ok(()), + } +} + /// OAuth client credentials #[derive(Clone, Serialize, Deserialize)] pub struct OAuthClient { @@ -266,6 +369,10 @@ pub struct OAuthClient { pub tenant: Option<String>, #[serde(default = "default_grant_types")] pub grant_types: Vec<String>, + /// `Some(false)` keeps the id/secret out of client-credentials connections, so a + /// client-credentials grant only lets users bring their own. Absent means shared. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub share_client_credentials: Option<bool>, /// The Slack app's signing secret, which authenticates the requests Slack sends Windmill. #[serde( default, @@ -280,6 +387,16 @@ pub struct OAuthClient { pub pkce: Option<bool>, } +impl OAuthClient { + /// Every user with write access may connect as this entry's service account. + pub fn shares_client_credentials(&self) -> bool { + self.grant_types.iter().any(|g| g == "client_credentials") + && self.share_client_credentials != Some(false) + && !self.id.is_empty() + && !self.secret.is_empty() + } +} + impl std::fmt::Debug for OAuthClient { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("OAuthClient") @@ -291,6 +408,7 @@ impl std::fmt::Debug for OAuthClient { .field("login_config", &self.login_config) .field("tenant", &self.tenant) .field("grant_types", &self.grant_types) + .field("share_client_credentials", &self.share_client_credentials) .field( "signing_secret", &self.signing_secret.as_ref().map(|_| "***"), @@ -330,7 +448,10 @@ impl std::fmt::Debug for AllClients { .field("logins", &self.logins) .field("connects", &self.connects) .field("slack", &self.slack) - .field("slack_signing_secret", &self.slack_signing_secret.as_ref().map(|_| "***")) + .field( + "slack_signing_secret", + &self.slack_signing_secret.as_ref().map(|_| "***"), + ) .finish() } } @@ -531,11 +652,9 @@ pub async fn build_client_credentials_oauth_client( // leaves the server. Only entries that explicitly enable the // client_credentials grant qualify, so an authorization-code-only client's // secret is never reused for this flow. - let instance_cc_creds = instance_entry.as_ref().filter(|e| { - e.grant_types.iter().any(|g| g == "client_credentials") - && !e.id.is_empty() - && !e.secret.is_empty() - }); + let instance_cc_creds = instance_entry + .as_ref() + .filter(|e| e.shares_client_credentials()); // All-or-nothing: use the caller's credentials only when both id and secret // are present, otherwise fall back entirely to the instance entry. Never mix // a caller-supplied id with the admin secret (or vice versa). @@ -561,6 +680,7 @@ pub async fn build_client_credentials_oauth_client( .map(|e| e.grant_types.clone()) .unwrap_or_else(default_grant_types), tenant: instance_entry.as_ref().and_then(|e| e.tenant.clone()), + share_client_credentials: None, signing_secret: None, pkce: None, }; @@ -602,8 +722,7 @@ pub async fn resolve_instance_cc_credentials( .and_then(|v| serde_json::from_value(v.clone()).ok()); Ok(entry.and_then(|e| { - let cc_grant = e.grant_types.iter().any(|g| g == "client_credentials"); - if cc_grant && !e.id.is_empty() && !e.secret.is_empty() { + if e.shares_client_credentials() { // Token URL from the entry's connect_config (built by instance settings // from the connect_config_template), so the account row is // self-contained for refresh. @@ -1353,7 +1472,10 @@ mod tests { want ); let sandbox = registry["salesforce"].as_sandbox().unwrap(); - assert_eq!(sandbox.connect_fields, registry["salesforce"].connect_fields); + assert_eq!( + sandbox.connect_fields, + registry["salesforce"].connect_fields + ); let quickbooks = serde_json::json!({"callback": {"realmId": "9130"}}); let got = connect_resource_fields(&quickbooks, &fields("quickbooks")); @@ -1563,4 +1685,87 @@ mod tests { assert!(!is_instance_templated_cc(CC_REGISTRY, "visma")); assert!(!is_instance_templated_cc(CC_REGISTRY, "my_custom_thing")); } + + #[test] + fn share_client_credentials_absent_means_shared() { + let entry = |extra: serde_json::Value| -> OAuthClient { + let mut v = serde_json::json!({ "id": "a", "secret": "b", + "grant_types": ["authorization_code", "client_credentials"] }); + v.as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + serde_json::from_value(v).unwrap() + }; + assert!(entry(serde_json::json!({})).shares_client_credentials()); + assert!( + !entry(serde_json::json!({ "share_client_credentials": false })) + .shares_client_credentials() + ); + assert!( + !entry(serde_json::json!({ "grant_types": ["authorization_code"] })) + .shares_client_credentials() + ); + } + + #[test] + fn validate_oauths_setting_names_each_bad_entry() { + let registry = r#"{ + "github": { "auth_url": "https://github.com/login/oauth/authorize", + "token_url": "https://github.com/login/oauth/access_token" }, + "coupa": { "grant_types": ["client_credentials"], + "connect_config_template": { "label": "Coupa instance", "placeholder": "x", + "token_url": "https://{instance}.coupahost.com/oauth2/token" } }, + "ms_teams": { "connect_config_template": { "label": "Microsoft Entra tenant", + "placeholder": "x", "extra_params_key": "tenant", + "token_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/token" } } + }"#; + let ok = |v: serde_json::Value| validate_oauths_setting(&v, None, registry); + assert!(ok(serde_json::Value::Null).is_ok()); + assert!(ok(serde_json::json!({ + "github": { "id": "a", "secret": "b" }, + "coupa": { "id": "a", "secret": "b", "grant_types": ["client_credentials"], + "connect_config": { "token_url": "https://acme.coupahost.com/oauth2/token", + "extra_params": { "instance": "acme" } } }, + "custom": { "id": "a", "secret": "b", "grant_types": ["client_credentials"], + "connect_config": { "token_url": "https://idp.example.com/token" } }, + "ms_teams": { "id": "a", "secret": "b", "tenant": "contoso" } + })) + .is_ok()); + assert!(ok(serde_json::json!({ + "coupa": { "id": "a", "secret": "b", "grant_types": ["client_credentials"], + "connect_config": { "token_url": "https://acme.coupahost.com/oauth2/token" } } + })) + .is_ok()); + assert!(ok(serde_json::json!({ + "coupa": { "id": "a", "secret": "b", "grant_types": ["client_credentials"], + "connect_config": { "token_url": "https://.coupahost.com/oauth2/token", + "extra_params": { "instance": "" } } } + })) + .unwrap_err() + .contains("Coupa instance is required")); + + let err = ok(serde_json::json!({ + "github": { "id": "a", "secret": "b", "grant_types": ["client_credentials"] }, + "coupa": { "id": "a", "secret": "b", "grant_types": ["client_credentials"] }, + "custom": { "id": "a", "secret": "b", "grant_types": ["client_credentials"] }, + "broken": { "id": 1 } + })) + .unwrap_err(); + for name in [ + "github:", + "coupa: Coupa instance is required", + "custom:", + "broken:", + ] { + assert!(err.contains(name), "{name} missing from: {err}"); + } + + // An unchanged bad entry, saved before the check existed, does not block the save. + let stored = serde_json::json!({ "broken": { "id": 1 } }); + let next = + serde_json::json!({ "broken": { "id": 1 }, "github": { "id": "a", "secret": "b" } }); + assert!(validate_oauths_setting(&next, Some(&stored), registry).is_ok()); + let edited = serde_json::json!({ "broken": { "id": 2 } }); + assert!(validate_oauths_setting(&edited, Some(&stored), registry).is_err()); + } } diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index da062edb26..6623eff418 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -75,7 +75,7 @@ use windmill_common::{ add_virtual_items_if_necessary, FlowModule, FlowModuleValue, FlowValue, InputTransform, Retry, StopAfterIf, }, - jobs::{runnable_ref_to_payload, JobKind, JobPayload, RawCode}, + jobs::{runnable_ref_to_payload, JobKind, JobPayload, RawCode, RunOrigin}, min_version::{MIN_VERSION_IS_AT_LEAST_1_432, MIN_VERSION_IS_AT_LEAST_1_440}, runnable_ref::RunnableRef, schedule::Schedule, @@ -84,8 +84,9 @@ use windmill_common::{ utils::{not_found_if_none, report_critical_error, StripPath, WarnAfterExt}, worker::{ to_raw_value, CLOUD_HOSTED, DEPENDENCY_JOB_TAG, DISABLE_FLOW_SCRIPT, NO_LOGS, - PREVIEW_TAGS_OVERRIDE, WORKER_PULL_QUERIES, WORKER_PULL_QUERIES_FAIRNESS, - WORKER_SUSPENDED_PULL_QUERY, WORKSPACE_FAIRNESS_OVERLOADED, + PREVIEW_TAGS_OVERRIDE, WORKER_CONFIG, WORKER_PULL_QUERIES, WORKER_PULL_QUERIES_FAIRNESS, + WORKER_SUSPENDED_PULL_QUERY, WORKER_SUSPENDED_PULL_QUERY_FAIRNESS, + WORKSPACE_FAIRNESS_OVERLOADED, }, DB, METRICS_ENABLED, }; @@ -669,40 +670,63 @@ pub async fn push_periodic_bash_job<'c>( Ok(uuid) } -pub async fn cancel_persistent_script_jobs<'c>( +/// `admit` is called with the runs each batch found, before any of them is touched, and returns +/// the ones to cancel; an error from it cancels none of that batch. The cancel itself runs on the +/// root pool, so `admit` is where the caller's access to those runs must be checked. +pub async fn cancel_persistent_script_jobs<F, Fut>( username: &str, reason: Option<String>, script_path: &str, w_id: &str, db: &Pool<Postgres>, -) -> error::Result<Vec<Uuid>> { + mut admit: F, +) -> error::Result<Vec<Uuid>> +where + F: FnMut(Vec<Uuid>) -> Fut, + Fut: Future<Output = error::Result<Vec<Uuid>>>, +{ // There can be only one perpetual script run per 10 seconds window. We execute the cancel twice with 5s interval // to avoid the case of a job _about to be restarted_ when the first cancel is run. - let cancelled_job_ids_first_batch = - cancel_persistent_script_jobs_internal(username, reason.clone(), script_path, w_id, db) - .await?; + let cancelled_job_ids_first_batch = cancel_persistent_script_jobs_internal( + username, + reason.clone(), + script_path, + w_id, + db, + &mut admit, + ) + .await?; sleep(std::time::Duration::from_secs(5)).await; - let cancelled_job_ids_second_batch = - cancel_persistent_script_jobs_internal(username, reason.clone(), script_path, w_id, db) - .await?; + let cancelled_job_ids_second_batch = cancel_persistent_script_jobs_internal( + username, + reason.clone(), + script_path, + w_id, + db, + &mut admit, + ) + .await?; return Ok(cancelled_job_ids_first_batch .into_iter() .chain(cancelled_job_ids_second_batch) .collect_vec()); } -async fn cancel_persistent_script_jobs_internal<'c>( +async fn cancel_persistent_script_jobs_internal<F, Fut>( username: &str, reason: Option<String>, script_path: &str, w_id: &str, db: &Pool<Postgres>, -) -> error::Result<Vec<Uuid>> { - let mut tx = db.begin().await?; - - // we could have retrieved the job IDs in the first query where we retrieve the hashes, but just in case a job was inserted in the queue right in-between the two above query, we re-do the fetch here + admit: &mut F, +) -> error::Result<Vec<Uuid>> +where + F: FnMut(Vec<Uuid>) -> Fut, + Fut: Future<Output = error::Result<Vec<Uuid>>>, +{ // Only the loops: a dependency job of this script shares its path, and a run of a version that - // does not restart itself ends on its own. + // does not restart itself ends on its own. A run that ends before the cancel below reaches it + // is skipped by `cancel_job`; its restart is caught by the next batch. let jobs_to_cancel = sqlx::query_scalar::<_, Uuid>( "SELECT j.id FROM v2_job_queue q JOIN v2_job j USING (id) \ JOIN script s ON s.workspace_id = j.workspace_id AND s.hash = j.runnable_id \ @@ -711,10 +735,12 @@ async fn cancel_persistent_script_jobs_internal<'c>( ) .bind(w_id) .bind(script_path) - .fetch_all(&mut *tx) + .fetch_all(db) .await?; - // Then we cancel all the jobs currently in the queue, one by one + let jobs_to_cancel = admit(jobs_to_cancel).await?; + + let mut tx = db.begin().await?; for queued_job_id in jobs_to_cancel.clone() { let (new_tx, _) = cancel_job( username, @@ -798,7 +824,7 @@ async fn restart_perpetual_runs_at_path( // run, below. let script = RunnableRef::from_path(script_path, false)?; let (mut payload, tag, _, _, timeout, on_behalf_of) = - script_path_to_payload(&script, None, db.clone(), w_id, None).await?; + script_path_to_payload(&script, RunOrigin::Deployed, None, db.clone(), w_id, None).await?; // A replacement continues a loop rather than answering a trigger, and every perpetual restart // is pushed without debouncing for that reason. Deployed settings here would debounce the // loops at this path against each other and collapse those that share arguments into one. @@ -3572,7 +3598,7 @@ pub async fn push_error_handler<'a, 'c, T: Serialize + Send + Sync>( w_id }; let (payload, tag, on_behalf_of) = - runnable_ref_to_payload(on_failure, db, handler_w_id).await?; + runnable_ref_to_payload(on_failure, RunOrigin::Deployed, db, handler_w_id).await?; let mut extra = HashMap::new(); if let Some(schedule_path) = schedule_path { @@ -3766,7 +3792,8 @@ pub async fn push_success_handler<'a, 'c, T: Serialize + Send + Sync>( email: &str, priority: Option<i16>, ) -> windmill_common::error::Result<Uuid> { - let (payload, tag, on_behalf_of) = runnable_ref_to_payload(on_success, db, w_id).await?; + let (payload, tag, on_behalf_of) = + runnable_ref_to_payload(on_success, RunOrigin::Deployed, db, w_id).await?; let mut extra = HashMap::new(); if let Some(schedule_path) = schedule_path { @@ -5166,14 +5193,30 @@ async fn pull_single_job_and_mark_as_running_no_concurrency_limit<'c>( tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; return Ok((None, false)); } - let r = if suspend_first { + let r = if !suspend_first { + None + } else if WORKER_CONFIG.load().fairness_reserve { + // Parked WAC parents and parallelism-capped flow branches resume only through this + // pull, so a reserve must resume the ones it started, but never the overloaded + // workspace's. Refreshed here too: after a successful resume the worker keeps + // resuming first, and would never reach the refresh below. + crate::workspace_fairness::maybe_refresh_overloaded(db); + let overloaded = WORKSPACE_FAIRNESS_OVERLOADED.load_full(); + if overloaded.is_empty() { + None + } else { + sqlx::query_as::<_, PulledJob>(&WORKER_SUSPENDED_PULL_QUERY_FAIRNESS.load()) + .bind(worker_name) + .bind(overloaded.as_slice()) + .fetch_optional(db) + .await? + } + } else { // tracing::info!("Pulling job with query: {}", query); sqlx::query_as::<_, PulledJob>(&query) .bind(worker_name) .fetch_optional(db) .await? - } else { - None }; if r.is_none() { @@ -5205,8 +5248,13 @@ async fn pull_single_job_and_mark_as_running_no_concurrency_limit<'c>( crate::workspace_fairness::maybe_refresh_overloaded(db); let overloaded = WORKSPACE_FAIRNESS_OVERLOADED.load_full(); let fairness_active = !overloaded.is_empty(); + let reserve = WORKER_CONFIG.load().fairness_reserve; - if fairness_active && !crate::workspace_fairness::should_admit_capped() { + if reserve && !fairness_active { + return Ok((None, false)); + } + + if fairness_active && (reserve || !crate::workspace_fairness::should_admit_capped()) { let fairness_queries = WORKER_PULL_QUERIES_FAIRNESS.load(); let overloaded_slice: &[String] = overloaded.as_slice(); for query in fairness_queries.iter() { @@ -5229,7 +5277,9 @@ async fn pull_single_job_and_mark_as_running_no_concurrency_limit<'c>( } } - if highest_priority_job.is_none() { + // A reserve worker never falls back: that fallback is how a capped workspace gets + // back onto a worker. + if highest_priority_job.is_none() && !reserve { // Standard pull path. Also acts as the fallback when fairness // filtered out every candidate: prefer running a capped // workspace's job over leaving a worker idle. (The cap is @@ -5797,10 +5847,9 @@ pub fn tag_reads_flow_expr(tag: &str) -> bool { tag.contains("$flow_expr[") } -/// Renders the value at the dotted `path` below `root` as a dynamic tag component, shared by -/// `$args[...]` and `$flow_expr[...]`: its JSON text with surrounding quotes trimmed, and empty -/// once a segment is missing. Only object keys are followed, never array indexes. -pub fn render_tag_path(root: Option<&RawValue>, path: &str) -> String { +/// The JSON text of the value at the dotted `path` below `root`, empty once a segment is missing. +/// Only object keys are followed, never array indexes. +fn json_at_path(root: Option<&RawValue>, path: &str) -> String { let mut value = root.map(|x| x.get()).unwrap_or_default().to_string(); for part in path.split('.').filter(|p| !p.is_empty()) { match serde_json::from_str::<serde_json::Value>(&value) { @@ -5811,10 +5860,35 @@ pub fn render_tag_path(root: Option<&RawValue>, path: &str) -> String { } } } + value +} + +/// Renders the value at the dotted `path` below `root` as a dynamic tag component, shared by +/// `$args[...]` and `$flow_expr[...]`: its JSON text with surrounding quotes trimmed, and empty +/// once a segment is missing or holds `null`. An optional input left unset is `null`, and must +/// fall back like a missing one rather than name a queue `null` that no worker serves. +pub fn render_tag_path(root: Option<&RawValue>, path: &str) -> String { + let value = json_at_path(root, path); + if value.trim() == "null" { + return String::new(); + } value.trim_matches('"').to_string() } +/// Fills in the `$workspace` and `$args[...]` of a concurrency or debounce key. A `null` argument +/// renders as `null`, which the keys of already queued jobs were built with. pub fn interpolate_args(x: String, args: &PushArgs, workspace_id: &str) -> String { + interpolate_args_with(x, args, workspace_id, |root, path| { + json_at_path(root, path).trim_matches('"').to_string() + }) +} + +fn interpolate_args_with( + x: String, + args: &PushArgs, + workspace_id: &str, + render: impl Fn(Option<&RawValue>, &str) -> String, +) -> String { // Save this value to avoid parsing twice let workspaced = x.as_str().replace("$workspace", workspace_id).to_string(); if RE_ARG_TAG.is_match(&workspaced) { @@ -5831,7 +5905,7 @@ pub fn interpolate_args(x: String, args: &PushArgs, workspace_id: &str) -> Strin .or(args.extra.as_ref().and_then(|x| x.get(root))) }) .flatten(); - let arg_value = render_tag_path(root_value.map(|x| &**x), rest); + let arg_value = render(root_value.map(|x| &**x), rest); interpolated = interpolated.replace(format!("$args[{}]", arg_name).as_str(), &arg_value); } @@ -5863,7 +5937,13 @@ pub async fn resolve_push_tag( } else { workspace_id.to_string() }; - Some(interpolate_args(tag.to_string(), args, &tag_ws)) + Some(interpolate_args_with( + tag.to_string(), + args, + &tag_ws, + render_tag_path, + )) + .filter(|t| !t.is_empty()) } /// The tag a dependency job is routed to when the instance's `dependency_job_tag` setting is @@ -7342,6 +7422,8 @@ async fn push_inner<'c, 'd>( chat_input_enabled: None, memory_id: None, no_inherited_flow_env: false, + continued_on_error: vec![], + test_subflows: None, } } _ => { @@ -7742,6 +7824,8 @@ async fn push_inner<'c, 'd>( chat_input_enabled: None, memory_id: None, no_inherited_flow_env: false, + continued_on_error: vec![], + test_subflows: None, }; // The completed job's own scopes are gone with its `job_perms` row, so the restart // takes the flow's current setting (and the restarting caller's ceiling). @@ -8780,6 +8864,7 @@ fn create_restarted_module( flow_jobs: Some(new_flow_jobs), flow_jobs_success: new_flow_jobs_success, flow_jobs_duration: new_flow_jobs_timeline, + flow_jobs_labels: None, branch_chosen: None, branchall: Some(BranchAllStatus { branch: branch_or_iteration_n - 1, @@ -8818,6 +8903,10 @@ fn create_restarted_module( if let Some(new_flow_jobs_timeline) = new_flow_jobs_timeline.as_mut() { new_flow_jobs_timeline.truncate(branch_or_iteration_n); } + let mut new_flow_jobs_labels = module.flow_jobs_labels(); + if let Some(new_flow_jobs_labels) = new_flow_jobs_labels.as_mut() { + new_flow_jobs_labels.truncate(branch_or_iteration_n); + } Ok(FlowStatusModule::InProgress { id: module.id(), job: new_flow_jobs[new_flow_jobs.len() - 1], @@ -8829,6 +8918,7 @@ fn create_restarted_module( flow_jobs: Some(new_flow_jobs), flow_jobs_success: new_flow_jobs_success, flow_jobs_duration: new_flow_jobs_timeline, + flow_jobs_labels: new_flow_jobs_labels, branch_chosen: None, branchall: None, parallel, @@ -8893,6 +8983,7 @@ fn reuse_completed_zombie_module(module: FlowStatusModule) -> FlowStatusModule { flow_jobs, flow_jobs_success, flow_jobs_duration, + flow_jobs_labels, branch_chosen, agent_actions, agent_actions_success, @@ -8906,6 +8997,7 @@ fn reuse_completed_zombie_module(module: FlowStatusModule) -> FlowStatusModule { .map(|v| v.into_iter().map(|_| Some(true)).collect()), flow_jobs, flow_jobs_duration, + flow_jobs_labels, branch_chosen, approvers: vec![], failed_retries: vec![], @@ -9546,13 +9638,16 @@ mod render_tag_path_tests { ) } - // Existing `$args[...]` tags route on exactly these renderings. + // Existing `$args[...]` tags route on exactly these renderings, except that `null` now falls + // back like a missing value. #[test] fn renders_like_args_tags() { assert_eq!(render(r#""eu""#, ""), "eu"); assert_eq!(render(r#"{"a": {"b": "eu"}}"#, "a.b"), "eu"); assert_eq!(render(r#"{"n": 4}"#, "n"), "4"); - assert_eq!(render("null", ""), "null"); + assert_eq!(render("null", ""), ""); + assert_eq!(render(r#"{"a": null}"#, "a"), ""); + assert_eq!(render(r#""null""#, ""), "null"); assert_eq!(render(r#"{"a": 1}"#, "b.c"), ""); assert_eq!(render(r#"{"a": ["eu"]}"#, "a.0"), ""); assert_eq!(render_tag_path(None, "a"), ""); @@ -9573,6 +9668,14 @@ mod render_tag_path_tests { interpolate_args("$args[_MODULES]private".to_string(), &push_args, "ws"), "private" ); + + // Concurrency and debounce keys keep rendering `null`, as queued jobs' keys were built. + let args = HashMap::from([("r".to_string(), raw("null"))]); + let push_args = PushArgs { args: &args, extra: None }; + assert_eq!( + interpolate_args("k-$args[r]".to_string(), &push_args, "ws"), + "k-null" + ); } fn raw(json: &str) -> Box<RawValue> { diff --git a/backend/windmill-queue/src/tags.rs b/backend/windmill-queue/src/tags.rs index 6a9cfc1200..1c30146491 100644 --- a/backend/windmill-queue/src/tags.rs +++ b/backend/windmill-queue/src/tags.rs @@ -209,8 +209,7 @@ async fn is_dedicated_worker_tag_of( .await?; let of_workspace = |entry: &serde_json::Value| { let (ws, path) = entry.as_str()?.split_once(':')?; - (ws == workspace_id) - .then(|| WorkspacedPath { workspace_id: ws.to_string(), path: path.to_string() }) + (ws == workspace_id).then(|| WorkspacedPath::dedicated(ws, path)) }; let mut single = vec![]; let mut many = vec![]; diff --git a/backend/windmill-queue/src/variable_expiration.rs b/backend/windmill-queue/src/variable_expiration.rs index 5882806f9d..e897ccc7a0 100644 --- a/backend/windmill-queue/src/variable_expiration.rs +++ b/backend/windmill-queue/src/variable_expiration.rs @@ -12,7 +12,7 @@ use std::collections::{HashMap, HashSet}; use serde_json::value::RawValue; use sqlx::types::Json; -use windmill_common::jobs::runnable_ref_to_payload; +use windmill_common::jobs::{runnable_ref_to_payload, RunOrigin}; use windmill_common::runnable_ref::RunnableRef; use windmill_common::utils::{report_critical_error, report_recovered_critical_error}; use windmill_common::DB; @@ -123,15 +123,17 @@ async fn dispatch_expiring_variables_inner(db: &DB) { ) { (Some(error), _) => Err(error.clone()), (None, Err(e)) => Err(format!("{e:#}")), - (None, Ok(handler)) => runnable_ref_to_payload(&handler, db, &row.workspace_id) - .await - .map_err(|e| { - let error = format!("{e:#}"); - if handler.path().starts_with("hub/") { - failed_hub_handlers.insert(row.handler_path.clone(), error.clone()); - } - error - }), + (None, Ok(handler)) => { + runnable_ref_to_payload(&handler, RunOrigin::Deployed, db, &row.workspace_id) + .await + .map_err(|e| { + let error = format!("{e:#}"); + if handler.path().starts_with("hub/") { + failed_hub_handlers.insert(row.handler_path.clone(), error.clone()); + } + error + }) + } }; let handler = match handler { Ok(handler) => handler, diff --git a/backend/windmill-queue/src/workspace_fairness.rs b/backend/windmill-queue/src/workspace_fairness.rs index 8eb3a69394..0c5a468f81 100644 --- a/backend/windmill-queue/src/workspace_fairness.rs +++ b/backend/windmill-queue/src/workspace_fairness.rs @@ -143,9 +143,8 @@ //! the first iteration: with `p_c` correctly tightened, victims do get the //! slot they need *when they exist*, and absent victims, falling back to //! the capped pool is the right behaviour (otherwise the cluster -//! under-utilises itself for no benefit). Adding a reserve-capacity skip -//! is a fine-tuning lever for bursty victim arrival patterns and is left -//! as a follow-up. +//! under-utilises itself for no benefit). Reserve capacity is opt-in per +//! worker instead, see "Reserve workers" below. //! //! ### Degenerate cases //! @@ -248,6 +247,18 @@ //! cached state in one pull cycle (resetting `WORKSPACE_FAIRNESS_OVERLOADED` //! to empty and `WORKSPACE_FAIRNESS_ADMISSION_PPM` to 10_000 = "admit all"), //! so toggling the feature off without restarting workers is safe. +//! +//! ## 7. Reserve workers +//! +//! Admission only steers what a worker pulls *next*. A workspace whose jobs +//! already hold every worker (sync parents polling for children that need a +//! worker themselves) leaves no pull to steer, for as long as those jobs run. +//! A worker of a group whose config sets `fairness_reserve` pulls +//! nothing while the overloaded set is empty, and otherwise only the fairness +//! queries (ordinary and suspended-resume), with no fallback. It stays idle rather +//! than serving everyone while nothing is capped: a burst landing before the +//! refresh flags its workspace would otherwise take it too. Fairness must be +//! enabled, or the set stays empty and a reserve worker never pulls. #[cfg(feature = "private")] #[allow(unused)] diff --git a/backend/windmill-queue/tests/schedule_push.rs b/backend/windmill-queue/tests/schedule_push.rs index 0cda6d3766..7de6be09ff 100644 --- a/backend/windmill-queue/tests/schedule_push.rs +++ b/backend/windmill-queue/tests/schedule_push.rs @@ -66,6 +66,7 @@ mod schedule_push { scopes: None, token_prefix: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/windmill-store/src/resources.rs b/backend/windmill-store/src/resources.rs index d251486a5a..85600006ce 100644 --- a/backend/windmill-store/src/resources.rs +++ b/backend/windmill-store/src/resources.rs @@ -230,6 +230,11 @@ pub struct ListedResource { #[serde(skip_serializing_if = "Option::is_none")] #[sqlx(default)] pub draft_path: Option<String>, + /// The linked OAuth account's grant: `client_credentials` connects as the app, anything + /// else as the user who connected it. + #[serde(skip_serializing_if = "Option::is_none")] + #[sqlx(default)] + pub grant_type: Option<String>, } #[derive(Deserialize)] @@ -372,6 +377,7 @@ async fn list_resources( "variable.is_oauth", "variable.account", "account.refresh_error", + "account.grant_type", "account.scopes", "resource.created_by", "resource.edited_at", @@ -584,7 +590,7 @@ async fn list_resources( // Synthesized rows are the authed user's draft. is_draft: Some(true), }; - rows.push(ListedResource { resource, agent_memory, draft_path }); + rows.push(ListedResource { resource, agent_memory, draft_path, grant_type: None }); } } @@ -1255,6 +1261,8 @@ fn note_resource_write(w_id: &str, path: &str, resource_type: &str) { #[derive(Deserialize)] struct CreateResourceQuery { update_if_exists: Option<bool>, + #[serde(default)] + skip_ci_tests: bool, } async fn create_resource( authed: ApiAuthed, @@ -1438,6 +1446,10 @@ async fn create_resource( None, ) .await?; + if authed.is_admin { + windmill_common::git_sync_oss::approve_github_app_repo(&mut *tx, &w_id, &resource.path) + .await?; + } tx.commit().await?; handle_deployment_metadata( @@ -1458,7 +1470,7 @@ async fn create_resource( ); // Trigger CI tests for items that reference this resource - { + if !q.skip_ci_tests { let db2 = db.clone(); let path2 = resource.path.clone(); let email2 = authed.email.clone(); @@ -2134,6 +2146,7 @@ async fn update_resource( Extension(user_db): Extension<UserDB>, Extension(webhook): Extension<WebhookShared>, Path((w_id, path)): Path<(String, StripPath)>, + Query(ci): Query<windmill_dep_map::ci_tests::SkipCiTestsQuery>, Json(ns): Json<EditResource>, ) -> Result<String> { use sql_builder::prelude::*; @@ -2400,6 +2413,9 @@ async fn update_resource( None, ) .await?; + if authed.is_admin && ns.value.is_some() { + windmill_common::git_sync_oss::approve_github_app_repo(&mut *tx, &w_id, &npath).await?; + } tx.commit().await?; // Detect if this was a rename operation @@ -2449,7 +2465,7 @@ async fn update_resource( ); // Trigger CI tests for items that reference this resource - { + if !ci.skip_ci_tests { let db2 = db.clone(); let npath2 = npath.clone(); let email2 = authed.email.clone(); @@ -2674,6 +2690,9 @@ async fn set_resource_value( None, ) .await?; + if authed.is_admin { + windmill_common::git_sync_oss::approve_github_app_repo(&mut *tx, w_id, path).await?; + } tx.commit().await?; note_resource_write(w_id, path, &resource_type); @@ -4092,26 +4111,27 @@ async fn get_git_commit_hash( let Some(git_repo_resource_value) = git_repo_resource_value else { return Err(Error::NotFound(format!("Resource {} not found", path)).into()); }; + let caller = if authed.is_admin { + GitRemoteCaller::AdminOrSystem + } else { + GitRemoteCaller::NonAdmin + }; // App-backed repos store a tokenless URL, so the `ls-remote` below can't // authenticate. Reuse the poller's REST head lookup, which mints an // installation token server-side rather than embedding one in a URL here. // It returns `None` for a repo that isn't app-backed, which is exactly the - // ls-remote case below. - // - // Admin-only for the same reason as the archive route: the repository is - // named by the resource's own `url`, which anyone with write on its path - // controls, so reading it would let a caller aim the installation - // credential at any repository it can reach. + // ls-remote case below. It serves a non-admin only the repository an admin + // approved on the resource. #[cfg(all(feature = "enterprise", feature = "private"))] if git_repo_resource_value .get("is_github_app") .and_then(|v| v.as_bool()) .unwrap_or(false) { - require_admin(authed.is_admin, &authed.username)?; if let Some((_, commit_hash)) = - windmill_common::git_sync_ee::get_app_repo_head_for_autopull(&db, &w_id, path).await? + windmill_common::git_sync_ee::get_app_repo_head_for_autopull(&db, &w_id, path, caller) + .await? { return Ok(Json(GitCommitHashResponse { commit_hash })); } @@ -4121,18 +4141,14 @@ async fn get_git_commit_hash( .map_err(|e| { Error::BadRequest(format!("Invalid git repository resource format: {}", e)) })?; - let caller = if authed.is_admin { - GitRemoteCaller::AdminOrSystem - } else { - GitRemoteCaller::NonAdmin - }; git_resource.url = resolve_azure_devops_url(&db_with_opt_authed, &w_id, &git_resource.url, false, caller) .await?; // A credential is stored under the repository it was issued for, so a // resource repointed elsewhere finds none. Which credential can be attached - // is bounded by that; who may use it is bounded here, on the same terms as - // the installation credential above. + // is bounded by that; who may use it is bounded here: admins only, since + // nothing records an admin's approval of the URL as for the installation + // credential above. let plain_url = git_resource.url.clone(); git_resource.url = windmill_common::git_sync_oss::with_stored_credential(&db, &w_id, git_resource.url).await?; diff --git a/backend/windmill-store/src/var_resource_cache.rs b/backend/windmill-store/src/var_resource_cache.rs index 3e89f8579e..8fc05797c8 100644 --- a/backend/windmill-store/src/var_resource_cache.rs +++ b/backend/windmill-store/src/var_resource_cache.rs @@ -250,6 +250,9 @@ mod tests { fn is_operator(&self) -> bool { self.is_operator } + fn capabilities(&self) -> Option<windmill_common::roles::RoleCapabilities> { + None + } fn groups(&self) -> &[String] { &self.groups } diff --git a/backend/windmill-trigger-http/src/handler.rs b/backend/windmill-trigger-http/src/handler.rs index 21caab6e7c..20c51dffb4 100644 --- a/backend/windmill-trigger-http/src/handler.rs +++ b/backend/windmill-trigger-http/src/handler.rs @@ -18,7 +18,7 @@ use windmill_common::{ DB, }; use windmill_git_sync::{handle_deployment_metadata, DeployedObject}; -use windmill_trigger::{Trigger, TriggerCrud, TriggerData}; +use windmill_trigger::{handler::trigger_save_runnables, Trigger, TriggerCrud, TriggerData}; pub async fn increase_trigger_version(tx: &mut PgConnection) -> Result<()> { sqlx::query!("SELECT nextval('http_trigger_version_seq')") @@ -294,6 +294,16 @@ pub async fn create_many_http_triggers( .validate_new(&db, &w_id, &new_http_trigger.config) .await .map_err(|err| error_wrapper(&new_http_trigger.config.route_path, err))?; + let new = trigger_save_runnables::<HttpTrigger>(new_http_trigger)?; + windmill_api_auth::composed::check_new_hub_paths(&new, &[], &authed, &db, &w_id) + .await + .map_err(|err| match err { + Error::PermissionDenied(msg) => Error::PermissionDenied(format!( + "Error occurred for HTTP route at route path: {}, error: {msg}", + new_http_trigger.config.route_path + )), + err => err, + })?; let route_path_key = check_if_route_exist(&db, &new_http_trigger.config, &w_id, None).await?; diff --git a/backend/windmill-trigger-http/src/lib.rs b/backend/windmill-trigger-http/src/lib.rs index e9dfbd405a..e39828dfd8 100644 --- a/backend/windmill-trigger-http/src/lib.rs +++ b/backend/windmill-trigger-http/src/lib.rs @@ -58,8 +58,47 @@ pub struct TriggerRoute { pub mode: TriggerMode, } +/// The routes of one HTTP method. Workspaced routes are looked up first, so a route a workspace +/// serves under its own `/{workspace_id}/` prefix is never answered by an instance-wide route, +/// whatever their patterns, and a conflict between the two cannot drop either. +pub struct MethodRouter<T> { + workspaced: matchit::Router<T>, + instance_wide: matchit::Router<T>, +} + +impl<T> Default for MethodRouter<T> { + fn default() -> Self { + Self { workspaced: matchit::Router::new(), instance_wide: matchit::Router::new() } + } +} + +impl<T> MethodRouter<T> { + pub fn insert( + &mut self, + workspaced: bool, + path: String, + value: T, + ) -> std::result::Result<(), matchit::InsertError> { + if workspaced { + &mut self.workspaced + } else { + &mut self.instance_wide + } + .insert(path, value) + } + + pub fn at<'m, 'p>( + &'m self, + path: &'p str, + ) -> std::result::Result<matchit::Match<'m, 'p, &'m T>, matchit::MatchError> { + self.workspaced + .at(path) + .or_else(|_| self.instance_wide.at(path)) + } +} + pub struct RoutersCache { - pub routers: HashMap<HttpMethod, matchit::Router<TriggerRoute>>, + pub routers: HashMap<HttpMethod, MethodRouter<TriggerRoute>>, pub version: i64, /// `HTTP_ROUTERS_INVALIDATIONS` as of the moment these rows were read. A rebuild that /// started before an invalidation publishes a count behind the current one, which is what @@ -343,21 +382,25 @@ pub async fn refresh_routers( .fetch_all(db) .await?; - let mut router = matchit::Router::new(); + let mut router = MethodRouter::default(); let http_route_workspaced = HTTP_ROUTE_WORKSPACED_ROUTE.load(std::sync::atomic::Ordering::Relaxed); for trigger in triggers { - let full_path = - if trigger.workspaced_route || *CLOUD_HOSTED || http_route_workspaced { - format!("/{}/{}", trigger.workspace_id, trigger.route_path) - } else { - format!("/{}", trigger.route_path) - }; + let workspaced = trigger.workspaced_route || *CLOUD_HOSTED || http_route_workspaced; + let full_path = if workspaced { + format!("/{}/{}", trigger.workspace_id, trigger.route_path) + } else { + format!("/{}", trigger.route_path) + }; if trigger.is_static_website { router - .insert(format!("{}/*wm_subpath", full_path), trigger.clone()) + .insert( + workspaced, + format!("{}/*wm_subpath", full_path), + trigger.clone(), + ) .unwrap_or_else(|e| { tracing::warn!( "Failed to consider HTTP route {}/*wm_subpath: {:?}", @@ -367,7 +410,7 @@ pub async fn refresh_routers( }); } router - .insert(full_path.clone(), trigger.clone()) + .insert(workspaced, full_path.clone(), trigger.clone()) .unwrap_or_else(|e| { tracing::warn!("Failed to consider HTTP route {}: {:?}", full_path, e,); }); @@ -492,6 +535,33 @@ mod tests { validate_allowed_origins, MAX_ALLOWED_ORIGINS, MAX_ALLOWED_ORIGIN_LEN, }; + #[test] + fn test_workspaced_route_takes_precedence_over_instance_wide() { + let mut router = MethodRouter::default(); + router + .insert(false, "/ws/gh/myrepo".to_string(), "instance") + .unwrap(); + router + .insert(false, "/ws/hooks/*rest".to_string(), "instance") + .unwrap(); + router + .insert(true, "/ws/gh/:repo".to_string(), "ws") + .unwrap(); + router + .insert(true, "/ws/hooks/:id".to_string(), "ws") + .unwrap(); + router + .insert(false, "/other/:id".to_string(), "instance") + .unwrap(); + + let at = |path| router.at(path).map(|m| *m.value).ok(); + assert_eq!(at("/ws/gh/myrepo"), Some("ws")); + assert_eq!(at("/ws/hooks/abc"), Some("ws")); + assert_eq!(at("/ws/hooks/abc/def"), Some("instance")); + assert_eq!(at("/other/1"), Some("instance")); + assert_eq!(at("/nothing"), None); + } + #[test] fn test_request_type_backward_compatibility() { // Test with new request_type field diff --git a/backend/windmill-trigger-websocket/src/handler.rs b/backend/windmill-trigger-websocket/src/handler.rs index bdfb9e20a7..873cc8c4ea 100644 --- a/backend/windmill-trigger-websocket/src/handler.rs +++ b/backend/windmill-trigger-websocket/src/handler.rs @@ -9,6 +9,7 @@ use windmill_common::DB; use windmill_common::{ db::UserDB, error::{Error, Result}, + jobs::ChosenBy, runnable_ref::RunnableRef, worker::to_raw_value, }; @@ -32,29 +33,33 @@ fn check_secondary_runnable_scopes( authed: &ApiAuthed, config: &WebsocketConfigRequest, ) -> Result<()> { - let check = |runnable: RunnableRef| { + for runnable in secondary_runnables(&config.url, config.initial_messages.as_deref()) { + let runnable = runnable?; let kind = if runnable.is_flow() { "flows" } else { "scripts" }; - check_scopes(authed, || format!("jobs:run:{kind}:{}", runnable.path())) - }; - if let Some(runnable) = RunnableRef::from_ws_url(&config.url) { - check(runnable?)?; - } - if let Some(messages) = config.initial_messages.as_ref() { - for msg in messages { - if let Ok(InitialMessage::RunnableResult { path, is_flow, .. }) = - serde_json::from_value::<InitialMessage>(msg.clone()) - { - check(RunnableRef::from_path(&path, is_flow)?)?; - } - } + check_scopes(authed, || format!("jobs:run:{kind}:{}", runnable.path()))?; } Ok(()) } +fn secondary_runnables( + url: &str, + initial_messages: Option<&[serde_json::Value]>, +) -> Vec<Result<RunnableRef>> { + let mut runnables: Vec<_> = RunnableRef::from_ws_url(url).into_iter().collect(); + for msg in initial_messages.unwrap_or_default() { + if let Ok(InitialMessage::RunnableResult { path, is_flow, .. }) = + serde_json::from_value::<InitialMessage>(msg.clone()) + { + runnables.push(RunnableRef::from_path(&path, is_flow)); + } + } + runnables +} + #[async_trait] impl TriggerCrud for WebsocketTrigger { type TriggerConfig = WebsocketConfig; @@ -83,6 +88,18 @@ impl TriggerCrud for WebsocketTrigger { ]; const IS_ALLOWED_ON_CLOUD: bool = false; + fn config_runnables(config: &serde_json::Value) -> Vec<RunnableRef> { + let url = config + .get("url") + .and_then(|v| v.as_str()) + .unwrap_or_default(); + let messages = config.get("initial_messages").and_then(|v| v.as_array()); + secondary_runnables(url, messages.map(Vec::as_slice)) + .into_iter() + .flatten() + .collect() + } + fn get_deployed_object(path: String, parent_path: Option<String>) -> DeployedObject { DeployedObject::WebsocketTrigger { path, parent_path } } @@ -318,6 +335,7 @@ impl TriggerCrud for WebsocketTrigger { &runnable?, &db, authed.clone(), + ChosenBy::Caller, config.url_runnable_args.as_ref().map(to_raw_value).as_ref(), &workspace_id, ) diff --git a/backend/windmill-trigger-websocket/src/lib.rs b/backend/windmill-trigger-websocket/src/lib.rs index 04dd48b716..61d60c0e22 100644 --- a/backend/windmill-trigger-websocket/src/lib.rs +++ b/backend/windmill-trigger-websocket/src/lib.rs @@ -6,7 +6,7 @@ use sqlx::{types::Json as SqlxJson, FromRow}; use windmill_api_auth::ApiAuthed; use windmill_common::{ error::{Error, Result}, - jobs::JobTriggerKind, + jobs::{ChosenBy, JobTriggerKind}, runnable_ref::RunnableRef, triggers::{TriggerKind, TriggerMetadata}, worker::to_raw_value, @@ -195,6 +195,7 @@ pub async fn get_url_from_runnable_value( runnable: &RunnableRef, db: &DB, authed: ApiAuthed, + chosen_by: ChosenBy, args: Option<&Box<RawValue>>, workspace_id: &str, ) -> Result<String> { @@ -210,6 +211,7 @@ pub async fn get_url_from_runnable_value( db, None, authed, + chosen_by, workspace_id, runnable, PushArgsOwned { args, extra: None }, diff --git a/backend/windmill-trigger-websocket/src/listener.rs b/backend/windmill-trigger-websocket/src/listener.rs index 09a07d0488..170240f984 100644 --- a/backend/windmill-trigger-websocket/src/listener.rs +++ b/backend/windmill-trigger-websocket/src/listener.rs @@ -19,7 +19,7 @@ use tokio_tungstenite::{tungstenite, tungstenite::Message, MaybeTlsStream, WebSo use windmill_common::ssrf::SsrfValidationError; use windmill_common::{ error::{to_anyhow, Error, Result}, - jobs::JobTriggerKind, + jobs::{ChosenBy, JobTriggerKind}, runnable_ref::RunnableRef, triggers::TriggerMetadata, utils::report_critical_error, @@ -103,6 +103,7 @@ async fn connect_once( &runnable, db, authed, + ChosenBy::Deployed, args, &listening_trigger.workspace_id, ) @@ -246,6 +247,7 @@ async fn send_initial_messages( db, None, authed.clone(), + ChosenBy::Deployed, &listening_trigger.workspace_id, &RunnableRef::from_path(&path, is_flow)?, PushArgsOwned { args, extra: None }, @@ -561,6 +563,7 @@ impl Listener for WebsocketTrigger { db, None, authed, + ChosenBy::Deployed, &workspace_id, &runnable, args, @@ -591,6 +594,7 @@ impl Listener for WebsocketTrigger { &db_, None, authed, + ChosenBy::Deployed, &w_id, &runnable, args, diff --git a/backend/windmill-trigger/src/global_handler.rs b/backend/windmill-trigger/src/global_handler.rs index 36b1eb167a..cae38d935d 100644 --- a/backend/windmill-trigger/src/global_handler.rs +++ b/backend/windmill-trigger/src/global_handler.rs @@ -15,7 +15,7 @@ use windmill_common::{ db::{UserDB, DB}, error::{self, Error, Result}, feature_usage::log_feature_usage, - jobs::{delete_jobs, JobTriggerKind}, + jobs::{delete_jobs, ChosenBy, JobTriggerKind}, triggers::TriggerMetadata, }; @@ -220,6 +220,7 @@ pub async fn resume_suspended_trigger_jobs( Some(tx), Some(user_db.clone()), authed.clone(), + ChosenBy::Deployed, &w_id, &windmill_common::runnable_ref::RunnableRef::from_path( &trigger.script_path, diff --git a/backend/windmill-trigger/src/handler.rs b/backend/windmill-trigger/src/handler.rs index 3d7a4ea385..512ce51f82 100644 --- a/backend/windmill-trigger/src/handler.rs +++ b/backend/windmill-trigger/src/handler.rs @@ -12,10 +12,15 @@ use serde::{de::DeserializeOwned, Deserialize, Serialize}; use sql_builder::{bind::Bind, SqlBuilder}; use sqlx::{FromRow, PgConnection}; use std::fmt::Debug; -use windmill_api_auth::{build_scope_path_predicate, check_scopes, ApiAuthed}; +use windmill_api_auth::{ + build_scope_path_predicate, check_scopes, + composed::check_new_hub_paths, + ApiAuthed, +}; use windmill_common::{ db::UserDB, error::{Error, JsonResult, Result}, + runnable_ref::RunnableRef, trigger_history::{self, TriggerHistoryEvent, TriggerOperation, TriggerSource}, user_drafts::{ delete_all_drafts_for_path, delete_draft_only_for_path, delete_own_draft_for_path, @@ -137,6 +142,13 @@ pub trait TriggerCrud: Send + Sync + 'static { Ok(()) } + /// The runnables this kind's config names besides its target and error handler, read from + /// JSON: a request serializes, and a stored row's `to_jsonb` reads, under the same field names. + /// A path that does not parse is left out, as it never runs. + fn config_runnables(_config: &serde_json::Value) -> Vec<RunnableRef> { + Vec::new() + } + fn scope_domain_name() -> &'static str { &Self::ROUTE_PREFIX[1..] } @@ -476,6 +488,28 @@ pub trait TriggerCrud: Send + Sync + 'static { } } +fn trigger_runnables<T: TriggerCrud>(trigger: &serde_json::Value) -> Vec<RunnableRef> { + let str_field = |name| trigger.get(name).and_then(|v| v.as_str()); + let is_flow = trigger + .get("is_flow") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let mut runnables = T::config_runnables(trigger); + runnables + .extend(str_field("script_path").and_then(|p| RunnableRef::from_path(p, is_flow).ok())); + runnables.extend( + str_field("error_handler_path").and_then(|p| RunnableRef::from_path(p, false).ok()), + ); + runnables +} + +/// The runnables a trigger save names, for `check_new_hub_paths`. +pub fn trigger_save_runnables<T: TriggerCrud>( + trigger: &TriggerData<T::TriggerConfigRequest>, +) -> Result<Vec<RunnableRef>> { + Ok(trigger_runnables::<T>(&serde_json::to_value(trigger)?)) +} + /// Append this mutation to `trigger_history`, diffing the row at `path` against /// `before`. /// @@ -562,6 +596,8 @@ async fn create_trigger<T: TriggerCrud>( handler .validate_new(&db, &workspace_id, &new_trigger.config) .await?; + let new = trigger_save_runnables::<T>(&new_trigger)?; + check_new_hub_paths(&new, &[], &authed, &db, &workspace_id).await?; let mut tx = user_db.begin(&authed).await?; @@ -835,6 +871,7 @@ async fn update_trigger<T: TriggerCrud>( handler .validate_edit(&db, &workspace_id, &edit_trigger.config, path) .await?; + let new_runnables = trigger_save_runnables::<T>(&edit_trigger)?; let mut tx = user_db.begin(&authed).await?; @@ -878,6 +915,17 @@ async fn update_trigger<T: TriggerCrud>( let before = trigger_history::snapshot_row(&mut *tx, T::TABLE_NAME, &workspace_id, path).await?; + check_new_hub_paths( + &new_runnables, + &before + .as_ref() + .map(trigger_runnables::<T>) + .unwrap_or_default(), + &authed, + &db, + &workspace_id, + ) + .await?; handler .update_trigger(&db, &mut *tx, &authed, &workspace_id, path, edit_trigger) diff --git a/backend/windmill-trigger/src/listener.rs b/backend/windmill-trigger/src/listener.rs index 7a2d2fa617..079b9f20e7 100644 --- a/backend/windmill-trigger/src/listener.rs +++ b/backend/windmill-trigger/src/listener.rs @@ -18,7 +18,7 @@ use tokio::sync::RwLock; use windmill_api_auth::ApiAuthed; use windmill_common::{ error::{Error, Result}, - jobs::JobTriggerKind, + jobs::{ChosenBy, JobTriggerKind}, runnable_ref::RunnableRef, triggers::{TriggerKind, TriggerMetadata}, utils::{report_critical_error, report_recovered_critical_error}, @@ -566,6 +566,7 @@ pub trait Listener: TriggerCrud + TriggerJobArgs { db, None, authed, + ChosenBy::Deployed, &listening_trigger.workspace_id, &runnable, args, diff --git a/backend/windmill-trigger/src/trigger_helpers.rs b/backend/windmill-trigger/src/trigger_helpers.rs index 2ce261468b..84dd8a1cfb 100644 --- a/backend/windmill-trigger/src/trigger_helpers.rs +++ b/backend/windmill-trigger/src/trigger_helpers.rs @@ -12,7 +12,9 @@ use windmill_common::{ error::Result, flows::{FlowModuleValue, Retry}, get_latest_deployed_hash_for_path, get_latest_flow_version_info_for_path, - jobs::{get_has_preprocessor_from_content_and_lang, script_path_to_payload, JobPayload}, + jobs::{ + get_has_preprocessor_from_content_and_lang, script_path_to_payload, ChosenBy, JobPayload, + }, runnable_ref::RunnableRef, scripts::{get_full_hub_script_by_id, ScriptHash, ScriptLang}, triggers::{ @@ -31,8 +33,8 @@ use windmill_api_jobs::execution::check_license_key_valid; use windmill_api_jobs::{ execution::{ check_tag_available_for_workspace, delete_job_metadata_after_use, - push_flow_job_by_path_into_queue, push_script_job_by_path_into_queue, result_to_response, - run_wait_result_internal, schedule_job_deletion, + push_flow_job_by_path_into_queue, push_script_job_by_path_into_queue, + result_to_http_response, run_wait_result_internal, schedule_job_deletion, }, types::RunJobQuery, }; @@ -507,6 +509,7 @@ pub async fn trigger_runnable_inner<'c>( tx_o: Option<sqlx::Transaction<'c, sqlx::Postgres>>, user_db: Option<UserDB>, authed: ApiAuthed, + chosen_by: ChosenBy, workspace_id: &str, runnable: &RunnableRef, mut args: PushArgsOwned, @@ -569,6 +572,7 @@ pub async fn trigger_runnable_inner<'c>( tx_o, user_db, authed, + chosen_by, workspace_id, runnable, args, @@ -598,6 +602,7 @@ pub async fn trigger_runnable( db: &DB, user_db: Option<UserDB>, authed: ApiAuthed, + chosen_by: ChosenBy, workspace_id: &str, runnable: &RunnableRef, args: PushArgsOwned, @@ -614,6 +619,7 @@ pub async fn trigger_runnable( None, user_db, authed, + chosen_by, workspace_id, runnable, args, @@ -635,6 +641,7 @@ pub async fn trigger_runnable_and_wait_for_result( db: &DB, user_db: Option<UserDB>, authed: ApiAuthed, + chosen_by: ChosenBy, workspace_id: &str, runnable: &RunnableRef, args: PushArgsOwned, @@ -650,6 +657,7 @@ pub async fn trigger_runnable_and_wait_for_result( None, user_db, authed, + chosen_by, workspace_id, runnable, args, @@ -678,7 +686,7 @@ pub async fn trigger_runnable_and_wait_for_result( None => {} } - result_to_response(result, success) + result_to_http_response(&db, &workspace_id, result, success).await } #[allow(dead_code)] @@ -686,6 +694,7 @@ pub async fn trigger_runnable_and_wait_for_raw_result( db: &DB, user_db: Option<UserDB>, authed: ApiAuthed, + chosen_by: ChosenBy, workspace_id: &str, runnable: &RunnableRef, args: PushArgsOwned, @@ -699,6 +708,7 @@ pub async fn trigger_runnable_and_wait_for_raw_result( db, user_db, authed, + chosen_by, workspace_id, runnable, args, @@ -716,6 +726,7 @@ async fn trigger_runnable_and_wait_for_job( db: &DB, user_db: Option<UserDB>, authed: ApiAuthed, + chosen_by: ChosenBy, workspace_id: &str, runnable: &RunnableRef, args: PushArgsOwned, @@ -731,6 +742,7 @@ async fn trigger_runnable_and_wait_for_job( None, user_db, authed, + chosen_by, workspace_id, runnable, args, @@ -775,6 +787,7 @@ pub async fn trigger_runnable_and_wait_for_raw_result_with_error_ctx( db: &DB, user_db: Option<UserDB>, authed: ApiAuthed, + chosen_by: ChosenBy, workspace_id: &str, runnable: &RunnableRef, args: PushArgsOwned, @@ -788,6 +801,7 @@ pub async fn trigger_runnable_and_wait_for_raw_result_with_error_ctx( db, user_db, authed, + chosen_by, workspace_id, runnable, args, @@ -816,6 +830,7 @@ async fn trigger_script_internal<'c>( tx_o: Option<sqlx::Transaction<'c, sqlx::Postgres>>, user_db: UserDB, authed: ApiAuthed, + chosen_by: ChosenBy, workspace_id: &str, script: &RunnableRef, args: PushArgsOwned, @@ -835,6 +850,7 @@ async fn trigger_script_internal<'c>( let run_query = RunJobQuery { job_id, suspended_mode, ..Default::default() }; let (uuid, resolved_delete_secs, tx_out) = push_script_job_by_path_into_queue( authed, + chosen_by, db.clone(), tx_o, user_db, @@ -852,6 +868,7 @@ async fn trigger_script_internal<'c>( tx_o, user_db, authed, + chosen_by, workspace_id, script, args, @@ -873,6 +890,7 @@ async fn trigger_script_with_retry_and_error_handler<'c>( tx_o: Option<sqlx::Transaction<'c, sqlx::Postgres>>, user_db: UserDB, authed: ApiAuthed, + chosen_by: ChosenBy, workspace_id: &str, script: &RunnableRef, args: PushArgsOwned, @@ -904,6 +922,7 @@ async fn trigger_script_with_retry_and_error_handler<'c>( let db_authed = UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() }; script_path_to_payload( script, + chosen_by.origin(authed.to_authed_ref()), Some(db_authed), db.clone(), &workspace_id, diff --git a/backend/windmill-types/Cargo.toml b/backend/windmill-types/Cargo.toml index 84fa209ddd..fb5eb1a458 100644 --- a/backend/windmill-types/Cargo.toml +++ b/backend/windmill-types/Cargo.toml @@ -26,3 +26,6 @@ bitflags.workspace = true [target.'cfg(not(target_arch = "wasm32"))'.dependencies] sqlx = { workspace = true, features = ["postgres"] } + +[dev-dependencies] +serde_yml.workspace = true diff --git a/backend/windmill-types/src/flow_status.rs b/backend/windmill-types/src/flow_status.rs index 71aba14cbb..2bdbc1aff5 100644 --- a/backend/windmill-types/src/flow_status.rs +++ b/backend/windmill-types/src/flow_status.rs @@ -46,6 +46,24 @@ pub struct FlowStatus { /// the worker then walks the ancestors as usual. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub no_inherited_flow_env: bool, + /// On a root flow: the steps, at any depth, that failed and that the flow went past + /// because of `continue_on_error`. Capped at `MAX_CONTINUED_ON_ERROR` entries. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub continued_on_error: Vec<ContinuedOnError>, + /// In a flow test run: deployed subflow path -> the flow value with the test's overrides + /// applied, run as a preview in place of the deployed subflow. Only the flow test route + /// writes it, and the worker passes it on only to flows that are part of the same test run: + /// a deployed subflow left as is, which may run as someone else, never gets it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub test_subflows: Option<HashMap<String, serde_json::Value>>, +} + +pub const MAX_CONTINUED_ON_ERROR: i32 = 100; + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct ContinuedOnError { + pub id: String, + pub job: Uuid, } #[derive(Serialize, Deserialize, Debug, Clone, Default)] @@ -190,6 +208,7 @@ struct UntaggedFlowStatusModule { flow_jobs: Option<Vec<Uuid>>, flow_jobs_success: Option<Vec<Option<bool>>>, flow_jobs_duration: Option<FlowJobsDuration>, + flow_jobs_labels: Option<Vec<Option<String>>>, branch_chosen: Option<BranchChosen>, branchall: Option<BranchAllStatus>, parallel: Option<bool>, @@ -198,7 +217,7 @@ struct UntaggedFlowStatusModule { failed_retries: Option<Vec<Uuid>>, skipped: Option<bool>, agent_actions: Option<Vec<AgentAction>>, - agent_actions_success: Option<Vec<bool>>, + agent_actions_success: Option<Vec<Option<bool>>>, } #[derive(Serialize, Deserialize, Debug, Clone)] @@ -274,6 +293,8 @@ pub enum FlowStatusModule { #[serde(skip_serializing_if = "Option::is_none")] flow_jobs_duration: Option<FlowJobsDuration>, #[serde(skip_serializing_if = "Option::is_none")] + flow_jobs_labels: Option<Vec<Option<String>>>, + #[serde(skip_serializing_if = "Option::is_none")] branch_chosen: Option<BranchChosen>, #[serde(skip_serializing_if = "Option::is_none")] branchall: Option<BranchAllStatus>, @@ -284,7 +305,7 @@ pub enum FlowStatusModule { #[serde(skip_serializing_if = "Option::is_none")] agent_actions: Option<Vec<AgentAction>>, #[serde(skip_serializing_if = "Option::is_none")] - agent_actions_success: Option<Vec<bool>>, + agent_actions_success: Option<Vec<Option<bool>>>, }, Success { id: String, @@ -296,6 +317,8 @@ pub enum FlowStatusModule { #[serde(skip_serializing_if = "Option::is_none")] flow_jobs_duration: Option<FlowJobsDuration>, #[serde(skip_serializing_if = "Option::is_none")] + flow_jobs_labels: Option<Vec<Option<String>>>, + #[serde(skip_serializing_if = "Option::is_none")] branch_chosen: Option<BranchChosen>, #[serde(default)] #[serde(skip_serializing_if = "Vec::is_empty")] @@ -306,7 +329,7 @@ pub enum FlowStatusModule { #[serde(skip_serializing_if = "Option::is_none")] agent_actions: Option<Vec<AgentAction>>, #[serde(skip_serializing_if = "Option::is_none")] - agent_actions_success: Option<Vec<bool>>, + agent_actions_success: Option<Vec<Option<bool>>>, }, Failure { id: String, @@ -318,13 +341,15 @@ pub enum FlowStatusModule { #[serde(skip_serializing_if = "Option::is_none")] flow_jobs_duration: Option<FlowJobsDuration>, #[serde(skip_serializing_if = "Option::is_none")] + flow_jobs_labels: Option<Vec<Option<String>>>, + #[serde(skip_serializing_if = "Option::is_none")] branch_chosen: Option<BranchChosen>, #[serde(skip_serializing_if = "Vec::is_empty")] failed_retries: Vec<Uuid>, #[serde(skip_serializing_if = "Option::is_none")] agent_actions: Option<Vec<AgentAction>>, #[serde(skip_serializing_if = "Option::is_none")] - agent_actions_success: Option<Vec<bool>>, + agent_actions_success: Option<Vec<Option<bool>>>, }, } @@ -372,6 +397,7 @@ impl<'de> Deserialize<'de> for FlowStatusModule { flow_jobs: untagged.flow_jobs, flow_jobs_success: untagged.flow_jobs_success, flow_jobs_duration: untagged.flow_jobs_duration, + flow_jobs_labels: untagged.flow_jobs_labels, branch_chosen: untagged.branch_chosen, branchall: untagged.branchall, parallel: untagged.parallel.unwrap_or(false), @@ -390,6 +416,7 @@ impl<'de> Deserialize<'de> for FlowStatusModule { flow_jobs: untagged.flow_jobs, flow_jobs_success: untagged.flow_jobs_success, flow_jobs_duration: untagged.flow_jobs_duration, + flow_jobs_labels: untagged.flow_jobs_labels, branch_chosen: untagged.branch_chosen, approvers: untagged.approvers.unwrap_or_default(), failed_retries: untagged.failed_retries.unwrap_or_default(), @@ -407,6 +434,7 @@ impl<'de> Deserialize<'de> for FlowStatusModule { flow_jobs: untagged.flow_jobs, flow_jobs_success: untagged.flow_jobs_success, flow_jobs_duration: untagged.flow_jobs_duration, + flow_jobs_labels: untagged.flow_jobs_labels, branch_chosen: untagged.branch_chosen, failed_retries: untagged.failed_retries.unwrap_or_default(), agent_actions: untagged.agent_actions, @@ -487,6 +515,15 @@ impl FlowStatusModule { } } + pub fn flow_jobs_labels(&self) -> Option<Vec<Option<String>>> { + match self { + FlowStatusModule::InProgress { flow_jobs_labels, .. } => flow_jobs_labels.clone(), + FlowStatusModule::Success { flow_jobs_labels, .. } => flow_jobs_labels.clone(), + FlowStatusModule::Failure { flow_jobs_labels, .. } => flow_jobs_labels.clone(), + _ => None, + } + } + pub fn flow_jobs_duration(&self) -> Option<FlowJobsDuration> { match self { FlowStatusModule::InProgress { flow_jobs_duration, .. } => flow_jobs_duration.clone(), @@ -556,7 +593,7 @@ impl FlowStatusModule { } } - pub fn agent_actions_success(&self) -> Option<Vec<bool>> { + pub fn agent_actions_success(&self) -> Option<Vec<Option<bool>>> { match self { FlowStatusModule::InProgress { agent_actions_success, .. } => { agent_actions_success.clone() @@ -614,6 +651,8 @@ impl FlowStatus { chat_input_enabled: f.chat_input_enabled, memory_id: None, no_inherited_flow_env: false, + continued_on_error: vec![], + test_subflows: None, } } diff --git a/backend/windmill-types/src/flows.rs b/backend/windmill-types/src/flows.rs index 82ebcdd1d8..d83028906f 100644 --- a/backend/windmill-types/src/flows.rs +++ b/backend/windmill-types/src/flows.rs @@ -541,12 +541,43 @@ pub struct ConstantDelay { #[serde(default)] pub struct ExponentialDelay { pub attempts: u32, + #[serde(deserialize_with = "deserialize_multiplier")] pub multiplier: u16, pub seconds: u16, #[serde(skip_serializing_if = "Option::is_none")] pub random_factor: Option<i8>, } +/// Accepts exactly the integers `u16` does: older workers parse the stored retry as `u16`, so +/// even `1.0` must stay refused. Only the error is reworded. +fn deserialize_multiplier<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u16, D::Error> { + struct Multiplier; + impl<'de> serde::de::Visitor<'de> for Multiplier { + type Value = u16; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a whole number from 0 to 65535") + } + fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<u16, E> { + u16::try_from(v).map_err(|_| E::custom(multiplier_error(v))) + } + fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<u16, E> { + u16::try_from(v).map_err(|_| E::custom(multiplier_error(v))) + } + fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<u16, E> { + Err(E::custom(multiplier_error(v))) + } + } + deserializer.deserialize_any(Multiplier) +} + +fn multiplier_error(got: impl std::fmt::Display) -> String { + format!( + "exponential retry multiplier must be a whole number from 0 to 65535, got {got}. \ + The delay before retry n is multiplier * seconds^n: the multiplier scales every delay, \ + seconds sets how fast they grow" + ) +} + impl Default for ExponentialDelay { fn default() -> Self { Self { attempts: 0, multiplier: 1, seconds: 0, random_factor: None } @@ -960,6 +991,14 @@ pub struct AgentTool { /// Flow module and MCP tools only. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub requires_approval: bool, + /// The agent is answered as soon as the tool's job starts, and gets its result in a later + /// message once it finishes. Only a flow module tool can run in the background. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub background: bool, + /// With `background` unset, the agent waits this many seconds for the tool's job, then is + /// answered as for a background tool. Flow module tools only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub background_after_secs: Option<u32>, pub value: ToolValue, } @@ -1105,6 +1144,10 @@ pub enum FlowModuleValue { parallelism: Option<InputTransform>, #[serde(skip_serializing_if = "Option::is_none")] squash: Option<bool>, + /// Evaluated once per iteration, with `flow_input.iter` set, into the text the run + /// viewers show for that iteration. Never fails the iteration. + #[serde(skip_serializing_if = "Option::is_none")] + iteration_label: Option<InputTransform>, }, WhileloopFlow { modules: Vec<FlowModule>, @@ -1231,6 +1274,7 @@ struct UntaggedFlowModuleValue { tool_inputs: Option<HashMap<String, HashMap<String, InputTransform>>>, pass_flow_input_directly: Option<bool>, squash: Option<bool>, + iteration_label: Option<InputTransform>, max_iterations: Option<u32>, max_duration_secs: Option<u32>, #[serde(flatten)] @@ -1274,6 +1318,7 @@ impl<'de> Deserialize<'de> for FlowModuleValue { parallel: untagged.parallel.unwrap_or(false), parallelism: untagged.parallelism, squash: untagged.squash, + iteration_label: untagged.iteration_label, }), "whileloopflow" => Ok(FlowModuleValue::WhileloopFlow { modules: untagged @@ -1740,6 +1785,29 @@ mod tests { assert_eq!(serde_json::to_value(&retry).unwrap(), input); } + #[test] + fn exponential_retry_multiplier_error_is_clear() { + for multiplier in [json!(0.4), json!(1.0), json!(70000), json!(-1)] { + let input = + json!({ "exponential": { "attempts": 3, "multiplier": multiplier, "seconds": 2 } }); + let err = serde_json::from_value::<Retry>(input) + .unwrap_err() + .to_string(); + assert!( + err.contains("retry multiplier must be a whole number"), + "{err}" + ); + } + let input = json!({ "exponential": { "attempts": 3, "multiplier": 65535, "seconds": 2 } }); + assert_eq!( + serde_json::from_value::<Retry>(input) + .unwrap() + .exponential + .multiplier, + 65535 + ); + } + #[test] fn branch_without_skip_failure_keeps_failing_the_flow() { // An absent skip_failure means "a failing branch fails the flow" to the diff --git a/backend/windmill-types/tests/listable_script_openapi.rs b/backend/windmill-types/tests/listable_script_openapi.rs new file mode 100644 index 0000000000..0d5254b7e0 --- /dev/null +++ b/backend/windmill-types/tests/listable_script_openapi.rs @@ -0,0 +1,78 @@ +//! `openapi.yaml` describes the `/scripts/list` row by hand, so a field added to +//! `ListableScript` must also be added to its `ListableScript` schema, or every +//! generated client silently lacks it. + +use std::collections::BTreeSet; + +use serde_json::Value; +use windmill_types::scripts::{ListableScript, ScriptHash, ScriptKind, ScriptLang}; +use windmill_types::user_drafts::DraftUserRef; + +fn listable_script(populated: bool) -> ListableScript { + let some = |s: &str| populated.then(|| s.to_string()); + ListableScript { + hash: ScriptHash(1), + path: "f/a/b".to_string(), + summary: String::new(), + created_at: chrono::Utc::now(), + archived: false, + extra_perms: serde_json::json!({}), + language: ScriptLang::Bun, + starred: false, + tag: None, + description: some("d"), + draft_only: populated.then_some(true), + has_deploy_errors: false, + ws_error_handler_muted: None, + auto_kind: some("lib"), + use_codebase: populated, + deployment_msg: some("m"), + kind: ScriptKind::Script, + labels: populated.then(|| vec!["l".to_string()]), + is_draft: populated, + draft_path: some("u/x/y"), + draft_users: populated.then(|| sqlx::types::Json(vec![DraftUserRef { username: None }])), + inherited_labels: populated.then(|| vec!["l".to_string()]), + } +} + +fn keys(script: &ListableScript) -> BTreeSet<String> { + match serde_json::to_value(script).unwrap() { + Value::Object(o) => o.into_iter().map(|(k, _)| k).collect(), + v => panic!("ListableScript serialized to {v}"), + } +} + +#[test] +fn listable_script_schema_matches_its_serialization() { + let spec: serde_yml::Value = serde_yml::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../windmill-api/openapi.yaml" + ))) + .unwrap(); + let schema = &spec["components"]["schemas"]["ListableScript"]; + let names = |v: &serde_yml::Value| -> BTreeSet<String> { + match v { + serde_yml::Value::Mapping(m) => { + m.keys().map(|k| k.as_str().unwrap().to_string()).collect() + } + serde_yml::Value::Sequence(s) => { + s.iter().map(|k| k.as_str().unwrap().to_string()).collect() + } + v => panic!("unexpected {v:?}"), + } + }; + let properties = names(&schema["properties"]); + let required = names(&schema["required"]); + + assert_eq!( + keys(&listable_script(true)), + properties, + "ListableScript's serialized fields and the properties of its openapi.yaml schema differ" + ); + assert_eq!( + keys(&listable_script(false)), + required, + "the fields ListableScript always serializes and the `required` list of its openapi.yaml schema differ" + ); +} diff --git a/backend/windmill-worker-volumes/Cargo.toml b/backend/windmill-worker-volumes/Cargo.toml index d94764e7cd..ea4970b457 100644 --- a/backend/windmill-worker-volumes/Cargo.toml +++ b/backend/windmill-worker-volumes/Cargo.toml @@ -26,6 +26,7 @@ serde_json.workspace = true regex.workspace = true lazy_static.workspace = true md-5.workspace = true +fs4.workspace = true [dev-dependencies] tempfile.workspace = true diff --git a/backend/windmill-worker-volumes/src/lib.rs b/backend/windmill-worker-volumes/src/lib.rs index 364795510a..f167676ea4 100644 --- a/backend/windmill-worker-volumes/src/lib.rs +++ b/backend/windmill-worker-volumes/src/lib.rs @@ -17,6 +17,10 @@ pub struct FileEntry { pub size: u64, #[serde(default, skip_serializing_if = "Option::is_none")] pub md5: Option<String>, + /// The object's ETag when this content was last read or written. A store's ETag need not be + /// a content hash (Azure's never is), so only the same store's ETag can vouch for a copy. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub e_tag: Option<String>, } pub fn compute_md5_hex(data: &[u8]) -> String { @@ -31,14 +35,14 @@ pub fn compute_md5_hex(data: &[u8]) -> String { hex } -/// Extract an MD5 hash from an S3 ETag, if it's a simple (non-multipart) ETag. +/// The content MD5 an ETag carries, if it is one: S3's for a single-part upload. Multipart S3 +/// ETags (`<hex>-<parts>`) and Azure's (`0x8D…`) are opaque and must not be compared with a hash. pub fn etag_to_md5(e_tag: Option<&str>) -> Option<String> { let tag = e_tag?.trim_matches('"'); - // Multipart ETags contain a '-' (e.g. "abc123-5"), skip those - if tag.contains('-') || tag.is_empty() { + if tag.len() != 32 || !tag.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } - Some(tag.to_string()) + Some(tag.to_ascii_lowercase()) } lazy_static::lazy_static! { @@ -52,6 +56,8 @@ lazy_static::lazy_static! { pub struct VolumeMount { pub name: String, pub target: String, + /// `volume:ro`: pulled without the volume's lease and never synced back. + pub read_only: bool, } /// A file's size and last change time. Sync-back trusts a pulled file's stored hash only while @@ -220,6 +226,15 @@ fn is_php_open_tag(trimmed_line: &str) -> bool { .is_some_and(|p| p.eq_ignore_ascii_case("<?php")) } +/// `ro` glued to `volume:` (`volume:ro <name> <target>`) marks a read-only mount. With a space +/// after the colon, `ro` is a volume's name: `volume: ro /tmp/x` mounts the volume `ro`. +pub fn split_read_only_flag(after_colon: &str) -> (bool, &str) { + match after_colon.strip_prefix("ro") { + Some(rest) if rest.starts_with(char::is_whitespace) => (true, rest), + _ => (false, after_colon), + } +} + /// Scans the leading comment block for `<prefix> volume: <name> <target>` lines, /// stopping at the first line that is neither blank nor a comment. A PHP script /// opens with `<?php`, which is not a comment, so that line is skipped like a blank @@ -238,14 +253,17 @@ pub fn parse_volume_annotations(content: &str, comment_prefix: &str) -> Vec<Volu } let after_prefix = trimmed[comment_prefix.len()..].trim(); if let Some(rest) = after_prefix.strip_prefix("volume:") { - let rest = rest.trim(); - let mut parts = rest.splitn(2, char::is_whitespace); + let (read_only, rest) = split_read_only_flag(rest); + let mut parts = rest.trim().splitn(2, char::is_whitespace); if let (Some(name), Some(target)) = (parts.next(), parts.next()) { let name = name.trim(); let target = target.trim(); if !name.is_empty() && !target.is_empty() { - volumes - .push(VolumeMount { name: name.to_string(), target: target.to_string() }); + volumes.push(VolumeMount { + name: name.to_string(), + target: target.to_string(), + read_only, + }); } } } @@ -263,7 +281,11 @@ mod tests { let result = parse_volume_annotations(content, "#"); assert_eq!( result, - vec![VolumeMount { name: "mydata".to_string(), target: "/tmp/data".to_string() }] + vec![VolumeMount { + name: "mydata".to_string(), + target: "/tmp/data".to_string(), + read_only: false + }] ); } @@ -273,7 +295,11 @@ mod tests { let result = parse_volume_annotations(content, "//"); assert_eq!( result, - vec![VolumeMount { name: "mydata".to_string(), target: "/tmp/data".to_string() }] + vec![VolumeMount { + name: "mydata".to_string(), + target: "/tmp/data".to_string(), + read_only: false + }] ); } @@ -284,7 +310,11 @@ mod tests { let result = parse_volume_annotations(content, "//"); assert_eq!( result, - vec![VolumeMount { name: "mydata".to_string(), target: "/tmp/data".to_string() }] + vec![VolumeMount { + name: "mydata".to_string(), + target: "/tmp/data".to_string(), + read_only: false + }] ); } @@ -295,9 +325,21 @@ mod tests { assert_eq!( result, vec![ - VolumeMount { name: "data1".to_string(), target: "/tmp/data1".to_string() }, - VolumeMount { name: "data2".to_string(), target: "/tmp/data2".to_string() }, - VolumeMount { name: "models".to_string(), target: "/opt/models".to_string() }, + VolumeMount { + name: "data1".to_string(), + target: "/tmp/data1".to_string(), + read_only: false + }, + VolumeMount { + name: "data2".to_string(), + target: "/tmp/data2".to_string(), + read_only: false + }, + VolumeMount { + name: "models".to_string(), + target: "/opt/models".to_string(), + read_only: false + }, ] ); } @@ -308,7 +350,37 @@ mod tests { let result = parse_volume_annotations(content, "#"); assert_eq!( result, - vec![VolumeMount { name: "mydata".to_string(), target: "/tmp/data".to_string() }] + vec![VolumeMount { + name: "mydata".to_string(), + target: "/tmp/data".to_string(), + read_only: false + }] + ); + } + + #[test] + fn parse_read_only_volume() { + let content = "# volume:ro models /opt/models\n# volume: ro /tmp/ro\n# volume:robots /tmp/r\ndef main():\n pass"; + let result = parse_volume_annotations(content, "#"); + assert_eq!( + result, + vec![ + VolumeMount { + name: "models".to_string(), + target: "/opt/models".to_string(), + read_only: true, + }, + VolumeMount { + name: "ro".to_string(), + target: "/tmp/ro".to_string(), + read_only: false + }, + VolumeMount { + name: "robots".to_string(), + target: "/tmp/r".to_string(), + read_only: false, + }, + ] ); } @@ -332,7 +404,11 @@ mod tests { let result = parse_volume_annotations(content, "#"); assert_eq!( result, - vec![VolumeMount { name: "data1".to_string(), target: "/tmp/data1".to_string() }] + vec![VolumeMount { + name: "data1".to_string(), + target: "/tmp/data1".to_string(), + read_only: false + }] ); } @@ -344,8 +420,16 @@ mod tests { assert_eq!( result, vec![ - VolumeMount { name: "data1".to_string(), target: "/tmp/data1".to_string() }, - VolumeMount { name: "data2".to_string(), target: "/tmp/data2".to_string() }, + VolumeMount { + name: "data1".to_string(), + target: "/tmp/data1".to_string(), + read_only: false + }, + VolumeMount { + name: "data2".to_string(), + target: "/tmp/data2".to_string(), + read_only: false + }, ] ); } @@ -357,7 +441,11 @@ mod tests { let result = parse_volume_annotations(content, "#"); assert_eq!( result, - vec![VolumeMount { name: "good".to_string(), target: "/tmp/good".to_string() }] + vec![VolumeMount { + name: "good".to_string(), + target: "/tmp/good".to_string(), + read_only: false + }] ); } @@ -367,7 +455,11 @@ mod tests { let result = parse_volume_annotations(content, "#"); assert_eq!( result, - vec![VolumeMount { name: "mydata".to_string(), target: "/tmp/data".to_string() }] + vec![VolumeMount { + name: "mydata".to_string(), + target: "/tmp/data".to_string(), + read_only: false + }] ); } @@ -380,6 +472,7 @@ mod tests { vec![VolumeMount { name: "mydata".to_string(), target: "/tmp/my data dir".to_string(), + read_only: false, }] ); } @@ -390,7 +483,11 @@ mod tests { let result = parse_volume_annotations(content, "#"); assert_eq!( result, - vec![VolumeMount { name: "my-data_v2".to_string(), target: "/tmp/data".to_string() }] + vec![VolumeMount { + name: "my-data_v2".to_string(), + target: "/tmp/data".to_string(), + read_only: false + }] ); } @@ -467,7 +564,11 @@ mod tests { let result = parse_volume_annotations(content, "//"); assert_eq!( result, - vec![VolumeMount { name: "agent-memory".to_string(), target: ".claude".to_string() }] + vec![VolumeMount { + name: "agent-memory".to_string(), + target: ".claude".to_string(), + read_only: false + }] ); } @@ -477,7 +578,11 @@ mod tests { let result = parse_volume_annotations(content, "#"); assert_eq!( result, - vec![VolumeMount { name: "data".to_string(), target: "data/models".to_string() }] + vec![VolumeMount { + name: "data".to_string(), + target: "data/models".to_string(), + read_only: false + }] ); } @@ -568,7 +673,11 @@ mod tests { #[test] fn validate_mounts_rejects_too_many() { let mounts: Vec<VolumeMount> = (0..11) - .map(|i| VolumeMount { name: format!("v{:02}", i), target: format!("t{}", i) }) + .map(|i| VolumeMount { + name: format!("v{:02}", i), + target: format!("t{}", i), + read_only: false, + }) .collect(); assert!(validate_volume_mounts(&mounts).is_err()); } @@ -576,8 +685,16 @@ mod tests { #[test] fn validate_mounts_rejects_duplicate_name() { let mounts = vec![ - VolumeMount { name: "data".to_string(), target: "/tmp/a".to_string() }, - VolumeMount { name: "data".to_string(), target: "/tmp/b".to_string() }, + VolumeMount { + name: "data".to_string(), + target: "/tmp/a".to_string(), + read_only: false, + }, + VolumeMount { + name: "data".to_string(), + target: "/tmp/b".to_string(), + read_only: false, + }, ]; assert!(validate_volume_mounts(&mounts).is_err()); } @@ -585,8 +702,16 @@ mod tests { #[test] fn validate_mounts_rejects_duplicate_target() { let mounts = vec![ - VolumeMount { name: "v1".to_string(), target: "/tmp/data".to_string() }, - VolumeMount { name: "v2".to_string(), target: "/tmp/data".to_string() }, + VolumeMount { + name: "v1".to_string(), + target: "/tmp/data".to_string(), + read_only: false, + }, + VolumeMount { + name: "v2".to_string(), + target: "/tmp/data".to_string(), + read_only: false, + }, ]; assert!(validate_volume_mounts(&mounts).is_err()); } @@ -594,8 +719,8 @@ mod tests { #[test] fn validate_mounts_ok() { let mounts = vec![ - VolumeMount { name: "v1".to_string(), target: "/tmp/a".to_string() }, - VolumeMount { name: "v2".to_string(), target: "/tmp/b".to_string() }, + VolumeMount { name: "v1".to_string(), target: "/tmp/a".to_string(), read_only: false }, + VolumeMount { name: "v2".to_string(), target: "/tmp/b".to_string(), read_only: false }, ]; assert!(validate_volume_mounts(&mounts).is_ok()); } diff --git a/backend/windmill-worker-volumes/src/volume_oss.rs b/backend/windmill-worker-volumes/src/volume_oss.rs index 07cd6906d2..aaa17a8330 100644 --- a/backend/windmill-worker-volumes/src/volume_oss.rs +++ b/backend/windmill-worker-volumes/src/volume_oss.rs @@ -25,15 +25,16 @@ pub async fn download_volume( } #[cfg(not(feature = "private"))] -pub fn volume_nsjail_mount(_local_dir: &Path, _target: &str) -> String { +pub fn volume_nsjail_mount(_local_dir: &Path, _target: &str, _read_only: bool) -> String { String::new() } #[cfg(not(feature = "private"))] -pub async fn sync_volume_back( +pub async fn sync_volume_back<F: std::future::Future<Output = error::Result<()>>>( _client: Arc<dyn ObjectStore>, _state: &VolumeState, _workspace_id: &str, + _open_write_window: F, ) -> error::Result<SyncStats> { Err(error::Error::internal_err( "Volumes are not available in this build".to_string(), diff --git a/backend/windmill-worker/loader.py b/backend/windmill-worker/loader.py index bf67266d87..fd9d2b1376 100644 --- a/backend/windmill-worker/loader.py +++ b/backend/windmill-worker/loader.py @@ -11,14 +11,14 @@ import time TEMP_SCRIPT_REFS = TEMP_SCRIPT_REFS_PLACEHOLDER class WindmillLoader(Loader): - def __init__(self, path): - self.path = path - def create_module(self, spec): return None def exec_module(self, module): - module.__path__ = self.path + # Must stay empty: PathFinder runs before WindmillFinder and would resolve + # submodules against any entry here (relative to the job dir, which holds + # loader.py, wrapper.py and the running script's f/<folder>/). + module.__path__ = [] return None @@ -31,7 +31,7 @@ class WindmillFinder(MetaPathFinder): return None l = len(splitted) # noqa: E741 if l <= 2: - return ModuleSpec(name, WindmillLoader(name)) + return ModuleSpec(name, WindmillLoader()) elif l > 2: script_path = "/".join(splitted) @@ -68,7 +68,7 @@ class WindmillFinder(MetaPathFinder): os.makedirs(folder, exist_ok=True) r = response.read().decode("utf-8") if r == "WINDMILL_IS_FOLDER": - return ModuleSpec(name, WindmillLoader(name)) + return ModuleSpec(name, WindmillLoader()) # Python parses .py as UTF-8 regardless of locale, so the # file has to be written as UTF-8. Without this the ANSI # code page on a Windows worker re-encodes every @@ -80,7 +80,7 @@ class WindmillFinder(MetaPathFinder): duration = time.time() - req_start if e.code != 404: print(f"Error fetching script {script_path}: HTTP {e.code} - {e.reason} - {duration}s") - return ModuleSpec(name, WindmillLoader(name)) + return ModuleSpec(name, WindmillLoader()) except Exception as e: duration = time.time() - req_start # Check if this is errno 104 (Connection reset by peer) and we have retries left @@ -89,7 +89,7 @@ class WindmillFinder(MetaPathFinder): time.sleep(3) continue print(f"Error fetching script {script_path}: {e} - {duration}s") - return ModuleSpec(name, WindmillLoader(name)) + return ModuleSpec(name, WindmillLoader()) diff --git a/backend/windmill-worker/src/ai/compaction.rs b/backend/windmill-worker/src/ai/compaction.rs index 99b746bcc9..b03cd37268 100644 --- a/backend/windmill-worker/src/ai/compaction.rs +++ b/backend/windmill-worker/src/ai/compaction.rs @@ -10,8 +10,8 @@ use windmill_ai::{ ai_providers::AIProvider, credentials::ProviderCredentials, - model_context::is_openai_reasoning_model, one_shot::{complete_text, OneShotRequest}, + providers::is_openai_reasoning_model, query_builder::QueryBuilder, types::{ContentPart, OpenAIContent, OpenAIMessage, TokenUsage}, }; @@ -572,6 +572,16 @@ async fn summarize_prefix( let assumed_credentials: Option<ProviderCredentials> = None; let credentials = assumed_credentials.as_ref().unwrap_or(request.credentials); + let mut vertex_token = None; + let vertex_credentials = windmill_ai::vertex_workload_identity::refresh_vertex_access_token( + credentials, + &mut vertex_token, + request.client, + ) + .await? + .map(|token| ProviderCredentials { api_key: Some(token.to_string()), ..credentials.clone() }); + let credentials = vertex_credentials.as_ref().unwrap_or(credentials); + // Summaries are rare enough that exchanging afresh costs less than threading the // agent loop's cached token through. let mut federated_token = None; @@ -758,6 +768,10 @@ mod tests { lowest_reasoning_effort(&AIProvider::OpenRouter, "openai/o3-mini"), Some("low") ); + assert_eq!( + lowest_reasoning_effort(&AIProvider::OpenAI, "gpt-6.1-sol"), + Some("low") + ); // Sending an effort to a model that takes none is a rejected request, and so is // `low` to a pro model, whose floor is its own. assert_eq!( diff --git a/backend/windmill-worker/src/ai/pause.rs b/backend/windmill-worker/src/ai/pause.rs index 130cf24766..1f20895ca1 100644 --- a/backend/windmill-worker/src/ai/pause.rs +++ b/backend/windmill-worker/src/ai/pause.rs @@ -1,8 +1,15 @@ -//! A call of a tool that requires approval, or of the built-in question tool, parks the agent -//! instead of running. The agent stores its conversation, releases its worker the way a +//! The agent parks, releasing its worker, while it waits on a person or on its background tools. +//! A call of a tool that requires approval, or of the built-in question tool, parks it until +//! someone answers; an answer the model gave while background tool jobs still run parks it until +//! one of them finishes. It stores its conversation and parks its own queue row the way a //! workflow-as-code parent does (`suspend_wac_parent`), and is pulled again when `suspend` reaches -//! 0 (an answer, or a rejection) or `suspend_until` passes (the request timing out). -//! `resume_suspended` answers it like a WAC approval, since its queue row is the one suspended. +//! 0 or `suspend_until` passes. +//! +//! An answer or a rejection reaches `suspend` through `resume_suspended`, which takes the agent's +//! row for a WAC approval. A finished background job reaches it through the monitor, which zeroes +//! the `suspend` of a parked agent once a job in its checkpoint's `waiting_on` has completed. Not +//! through `record_child_completion`: it clears every pending id of a parent it wakes, which fits a +//! WAC round but would drop the agent's other background jobs. //! //! The checkpoint row outlives the segment that reads it, so a job restarted after its worker died //! resumes from it again. It is deleted by the monitor once the job leaves the queue. @@ -24,6 +31,7 @@ use windmill_common::{ use windmill_queue::MiniPulledJob; use crate::ai::compaction::HistoryCheckpoint; +use crate::ai::tools::BackgroundJob; use crate::ai::utils::find_unique_tool_name; use crate::wac_executor::{end_wac_segment, suspend_wac_parent, WacPark}; @@ -33,6 +41,8 @@ pub(crate) const QUESTION_ENABLED_NAME: &str = "__wm_question"; /// Matches a suspended flow step's default. const DEFAULT_TIMEOUT_SECS: u32 = 1800; +/// A park on background jobs only is woken by the monitor; this only bounds the park. +const BACKGROUND_RECHECK_SECS: f64 = 3600.0; pub(crate) fn question_timeout(value: &QuestionToolValue) -> u32 { value.timeout.unwrap_or(DEFAULT_TIMEOUT_SECS).max(1) @@ -79,6 +89,7 @@ pub(crate) fn question_tool(timeout_secs: u32, existing: &[ToolDef]) -> Tool { mcp_source: None, requires_approval: false, question_timeout_secs: Some(timeout_secs), + background_after_secs: None, } } @@ -180,22 +191,79 @@ pub(crate) struct AgentCheckpoint { pub events: String, pub reasoning: String, pub next_iteration: usize, - pub pending: PendingPause, + /// The approval the agent waits on, if any. + pub pending: Option<PendingPause>, + #[serde(default)] + pub background: Vec<BackgroundJob>, + /// The model had given its answer: with nothing new from a background job, there is nothing + /// to ask it, so the agent parks again. + #[serde(default)] + pub answered: bool, + /// The model gave a structured answer, which stands unless it gives another. + #[serde(default)] + pub structured_answer: bool, /// `resume_job` rows never leave while the agent is queued, so each answer must skip the /// ones earlier parks already read. #[serde(default)] pub consumed_resume_rows: Vec<Uuid>, + /// Set by a new run of the same memory id while this one was parked: the agent ends with what + /// it has, its open request dropped, its background jobs and its memory now the new run's. + #[serde(default)] + pub handed_over: bool, +} + +// Saved to memory at park, where the turn may yet be taken over, cancelled or answered: true of +// the first two, and replaced by the answer in the third. +const DROPPED_APPROVAL: &str = "Not run: the approval request was left unanswered."; +const DROPPED_QUESTION: &str = "The question was left unanswered."; + +/// The answer to a request dropped because a new turn took the conversation over. +pub(crate) fn dropped_answer(pending: &PendingPause, actions: &[AgentAction]) -> Answer { + match &pending.request { + PendingRequest::Approval { .. } => Answer::Refuse(DROPPED_APPROVAL.to_string()), + PendingRequest::Question { .. } => Answer::Question(dropped_question(pending, actions)), + } +} + +fn dropped_question(pending: &PendingPause, actions: &[AgentAction]) -> OpenAIMessage { + question_message( + pending, + actions, + serde_json::json!({ "skipped": true, "message": DROPPED_QUESTION }), + ) +} + +/// The tool messages `dropped_answer` ends up giving the request's calls, so that the memory saved +/// at park already reads the way a new turn that takes over will find it. +pub(crate) fn dropped_messages( + pending: &PendingPause, + actions: &[AgentAction], +) -> Vec<OpenAIMessage> { + match &pending.request { + PendingRequest::Approval { calls } => calls + .iter() + .map(|call| OpenAIMessage { + role: "tool".to_string(), + content: Some(OpenAIContent::Text(DROPPED_APPROVAL.to_string())), + tool_call_id: Some(call.id.clone()), + ..Default::default() + }) + .collect(), + PendingRequest::Question { .. } => vec![dropped_question(pending, actions)], + } } pub(crate) async fn load_checkpoint( db: &DB, job_id: &Uuid, ) -> error::Result<Option<AgentCheckpoint>> { - let raw: Option<sqlx::types::Json<Box<serde_json::value::RawValue>>> = - sqlx::query_scalar("SELECT checkpoint FROM ai_agent_checkpoint WHERE job_id = $1") - .bind(job_id) - .fetch_optional(db) - .await?; + let raw = sqlx::query_scalar!( + r#"SELECT checkpoint AS "checkpoint: sqlx::types::Json<Box<serde_json::value::RawValue>>" + FROM ai_agent_checkpoint WHERE job_id = $1"#, + job_id + ) + .fetch_optional(db) + .await?; raw.map(|r| { serde_json::from_str(r.0.get()) .map_err(|e| Error::internal_err(format!("Invalid AI agent checkpoint: {e}"))) @@ -207,34 +275,63 @@ pub(crate) enum ParkOutcome { Parked, /// A cancel reached the queue row first, so nothing was written. Cancelled, + /// A background job finished before the park could be written, so the agent continues. + JobFinished, } -/// Park the agent until its approval is answered or expires. +/// Park the agent until its approval is answered or expires or, with no approval open, until the +/// monitor finds one of its `waiting_on` jobs completed. pub(crate) async fn park( db: &DB, conn: &Connection, job: &MiniPulledJob, checkpoint: &AgentCheckpoint, ) -> error::Result<ParkOutcome> { - let remaining_ms = (checkpoint.pending.expires_at - Utc::now()).num_milliseconds(); - let suspend_secs = (remaining_ms as f64 / 1000.0).max(1.0); + let suspend_secs = match &checkpoint.pending { + Some(pending) => { + let remaining_ms = (pending.expires_at - Utc::now()).num_milliseconds(); + (remaining_ms as f64 / 1000.0).max(1.0) + } + None => BACKGROUND_RECHECK_SECS, + }; + let running: Vec<Uuid> = checkpoint.background.iter().map(|b| b.job_id).collect(); + let waits_on_approval = checkpoint.pending.is_some(); let checkpoint = serde_json::to_value(checkpoint).map_err(|e| { Error::internal_err(format!("Failed to serialize AI agent checkpoint: {e}")) })?; let mut tx = db.begin().await?; - // One event: an answer, or a rejection, which zeroes `suspend` outright. + // One event wakes it: an answer, a rejection (which zeroes `suspend` outright), or a + // background job finishing. let segment_ms = match suspend_wac_parent(&mut tx, &job.id, &job.workspace_id, 1, suspend_secs).await? { WacPark::Parked(ms) => ms, WacPark::Cancelled(_) => return Ok(ParkOutcome::Cancelled), }; - sqlx::query( - "INSERT INTO ai_agent_checkpoint (job_id, workspace_id, checkpoint) VALUES ($1, $2, $3) - ON CONFLICT (job_id) DO UPDATE SET checkpoint = EXCLUDED.checkpoint", + // A job that completed since the loop last looked is delivered now rather than after a park + // and a monitor tick. While an approval is open, results wait for the answer anyway. + let waiting_on: Vec<Uuid> = if waits_on_approval { vec![] } else { running }; + if !waiting_on.is_empty() { + let finished = sqlx::query_scalar!( + r#"SELECT EXISTS (SELECT 1 FROM v2_job_completed WHERE id = ANY($1)) AS "finished!""#, + &waiting_on + ) + .fetch_one(&mut *tx) + .await?; + if finished { + tx.rollback().await?; + return Ok(ParkOutcome::JobFinished); + } + } + sqlx::query!( + "INSERT INTO ai_agent_checkpoint (job_id, workspace_id, checkpoint, waiting_on) + VALUES ($1, $2, $3, $4) + ON CONFLICT (job_id) DO UPDATE + SET checkpoint = EXCLUDED.checkpoint, waiting_on = EXCLUDED.waiting_on", + job.id, + &job.workspace_id, + checkpoint, + &waiting_on ) - .bind(&job.id) - .bind(&job.workspace_id) - .bind(&checkpoint) .execute(&mut *tx) .await?; tx.commit().await?; @@ -242,6 +339,30 @@ pub(crate) async fn park( Ok(ParkOutcome::Parked) } +/// Resume an agent that waits on no approval. `suspend` is zeroed, so `resume_suspended` refuses +/// answers while it runs, as `answer_pause` does for one with an approval. An answer the parked +/// row still accepted is marked read: no request was open, so none may take it later. +pub(crate) async fn resume_without_approval( + db: &DB, + job_id: &Uuid, + consumed_resume_rows: &mut Vec<Uuid>, +) -> error::Result<()> { + let mut tx = db.begin().await?; + sqlx::query!("UPDATE v2_job_queue SET suspend = 0 WHERE id = $1", job_id) + .execute(&mut *tx) + .await?; + let stray = sqlx::query_scalar!( + "SELECT id FROM resume_job WHERE job = $1 AND id <> ALL($2)", + job_id, + &*consumed_resume_rows + ) + .fetch_all(&mut *tx) + .await?; + tx.commit().await?; + consumed_resume_rows.extend(stray); + Ok(()) +} + pub(crate) enum Resumed { /// The answer, and whether it counts as a success on the run page. Answered(Answer, bool), @@ -272,23 +393,20 @@ pub(crate) async fn answer_pause( consumed_resume_rows: &mut Vec<Uuid>, ) -> error::Result<Resumed> { let mut tx = db.begin().await?; - sqlx::query("UPDATE v2_job_queue SET suspend = 0 WHERE id = $1") - .bind(job_id) + sqlx::query!("UPDATE v2_job_queue SET suspend = 0 WHERE id = $1", job_id) .execute(&mut *tx) .await?; - let rows: Vec<( - Uuid, - sqlx::types::Json<serde_json::Value>, - Option<String>, - bool, - )> = sqlx::query_as( - "SELECT id, value, approver, approved FROM resume_job - WHERE job = $1 AND id <> ALL($2) ORDER BY created_at ASC", + let rows = sqlx::query!( + r#"SELECT id, value AS "value: sqlx::types::Json<serde_json::Value>", approver, approved + FROM resume_job WHERE job = $1 AND id <> ALL($2) ORDER BY created_at ASC"#, + job_id, + &*consumed_resume_rows ) - .bind(job_id) - .bind(&*consumed_resume_rows) .fetch_all(&mut *tx) - .await?; + .await? + .into_iter() + .map(|r| (r.id, r.value, r.approver, r.approved)) + .collect::<Vec<_>>(); tx.commit().await?; consumed_resume_rows.extend(rows.iter().map(|(id, ..)| *id)); diff --git a/backend/windmill-worker/src/ai/tools.rs b/backend/windmill-worker/src/ai/tools.rs index 305d66fb76..693c39926b 100644 --- a/backend/windmill-worker/src/ai/tools.rs +++ b/backend/windmill-worker/src/ai/tools.rs @@ -2,8 +2,8 @@ use crate::ai::pause::{start_approval, start_question, PendingPause}; use crate::ai::stream_event_processor::StreamEventProcessor; use crate::ai::utils::{ add_message_to_conversation, execute_mcp_tool, get_step_name_from_flow, - update_flow_status_module_with_actions, update_flow_status_module_with_actions_success, - FlowContext, + set_flow_status_module_action_success_at, update_flow_status_module_with_actions, + update_flow_status_module_with_actions_success, FlowContext, }; use crate::common::{get_root_job_id, OccupancyMetrics}; use crate::result_processor::handle_non_flow_job_error; @@ -14,9 +14,14 @@ use crate::worker_flow::{ use crate::{create_job_dir, handle_queued_job, JobCompletedSender}; use anyhow::Context; use mappable_rc::Marc; +use serde::{Deserialize, Serialize}; use serde_json::value::RawValue; use sqlx::types::Json; -use std::{collections::HashMap, sync::Arc, time::Duration}; +use std::{ + collections::HashMap, + sync::Arc, + time::{Duration, Instant}, +}; use uuid::Uuid; use windmill_ai::{ai_types::OpenAIToolCall, query_builder::StreamEventSink, types::*}; use windmill_common::jobs::JobPayload; @@ -126,6 +131,7 @@ pub async fn execute_tool_calls( refuse_tool_call(&mut ctx, call, &refusal, &mut messages, final_events_str).await?; } + let mut started = Vec::new(); let mut calls = to_run.into_iter().peekable(); while let Some(tool_call) = calls.next() { // Stream tool call progress @@ -151,6 +157,25 @@ pub async fn execute_tool_calls( tool_call_id: Some(tool_call.id.clone()), ..Default::default() }); + // The answer ends the turn, but the history can be sent again after a background + // result, and a provider refuses a call left unanswered. + for skipped in calls.by_ref() { + messages.push(OpenAIMessage { + role: "tool".to_string(), + content: Some(OpenAIContent::Text( + "Not run: the structured answer ended this turn.".to_string(), + )), + tool_call_id: Some(skipped.id.clone()), + ..Default::default() + }); + } + // An action like a text answer's: the run page matches tagged messages to actions by + // position, and with background tools a run can go on after this answer. + actions.push(AgentAction::Message {}); + if let Some(parent_job) = ctx.parent_job { + update_flow_status_module_with_actions(ctx.db, parent_job, actions).await?; + update_flow_status_module_with_actions_success(ctx.db, parent_job, true).await?; + } messages.push(OpenAIMessage { role: "assistant".to_string(), content: Some(OpenAIContent::Text(tool_call.function.arguments.clone())), @@ -189,6 +214,11 @@ pub async fn execute_tool_calls( final_events_str, ) .await?; + } else if tool.module.is_some() && tool.background_after_secs == Some(0) { + started.push( + start_background_tool(&mut ctx, tool_call, tool, actions, &mut messages) + .await?, + ); } else if tool.module.is_some() { let mut batch = vec![(tool_call, tool)]; while let Some(next_call) = calls.peek() { @@ -201,6 +231,7 @@ pub async fn execute_tool_calls( t.def.function.name == next_call.function.name && t.mcp_source.is_none() && t.module.is_some() + && t.background_after_secs != Some(0) }) else { break; }; @@ -209,8 +240,15 @@ pub async fn execute_tool_calls( } batch.push((calls.next().unwrap(), next_tool)); } - execute_windmill_tools(&mut ctx, &batch, actions, &mut messages, final_events_str) - .await?; + execute_windmill_tools( + &mut ctx, + &batch, + actions, + &mut messages, + &mut started, + final_events_str, + ) + .await?; } else { return Err(Error::internal_err(format!( "Tool type not supported: {}", @@ -225,7 +263,7 @@ pub async fn execute_tool_calls( } } - Ok(ToolCallsOutcome { messages, final_content, used_structured_output_tool, pause }) + Ok(ToolCallsOutcome { messages, final_content, used_structured_output_tool, pause, started }) } /// A turn's calls: run now, refused with a message, or held for a person's answer. @@ -325,6 +363,187 @@ pub struct ToolCallsOutcome { pub used_structured_output_tool: bool, /// The turn asked a person something: the agent parks, those calls unanswered. pub pause: Option<PendingPause>, + /// Background tool calls this turn started. + pub started: Vec<BackgroundJob>, +} + +/// A background tool call, answered when its job started and still owed its result. +#[derive(Serialize, Deserialize, Clone, Debug)] +pub(crate) struct BackgroundJob { + pub call_id: String, + pub function_name: String, + pub arguments: String, + pub module_id: String, + pub job_id: Uuid, + /// Its position in the run's actions, which is where its outcome is recorded. + pub action_index: usize, + /// A nested agent's result is an envelope; the model gets its `output`. + pub is_agent: bool, + /// Started by an earlier turn this run took over: `action_index` is that turn's, so this run + /// records no outcome for it. + #[serde(default)] + pub adopted: bool, +} + +/// A background job that finished: whether it succeeded, and what the model is told it returned. +pub(crate) struct FinishedBackgroundJob { + pub job: BackgroundJob, + pub success: bool, + pub content: String, +} + +impl FinishedBackgroundJob { + /// What the model reads. Its call was answered when the job started, so the result comes as a + /// message of its own, tagged with the call's action for the run's trace. + pub fn message(&self) -> OpenAIMessage { + let job = &self.job; + let outcome = if self.success { "finished" } else { "failed" }; + OpenAIMessage { + role: "user".to_string(), + content: Some(OpenAIContent::Text(format!( + "Background tool `{}` (call {}, job {}) {outcome}. Result:\n{}", + job.function_name, job.call_id, job.job_id, self.content + ))), + agent_action: Some(AgentAction::ToolCall { + job_id: job.job_id, + function_name: job.function_name.clone(), + module_id: job.module_id.clone(), + }), + ..Default::default() + } + } + + /// The chat transcript row, shaped like a foreground tool's. + pub fn chat_row(&self) -> (String, MessageExtras) { + let job = &self.job; + let content = if self.success { + format!("Used {} tool", job.function_name) + } else { + format!("Error executing {}", job.function_name) + }; + let extras = MessageExtras { + tool_arguments: Some(job.arguments.clone()), + tool_result: Some(self.content.clone()), + ..Default::default() + }; + (content, extras) + } +} + +/// Take the background jobs that have finished out of `running`. +pub(crate) async fn take_finished_background_jobs( + db: &DB, + workspace_id: &str, + running: &mut Vec<BackgroundJob>, +) -> Result<Vec<FinishedBackgroundJob>, Error> { + let ids: Vec<Uuid> = running.iter().map(|b| b.job_id).collect(); + let completed = sqlx::query!( + "SELECT id, status = 'success' AS \"success!\", result AS \"result: Json<Box<RawValue>>\" + FROM v2_job_completed WHERE workspace_id = $1 AND id = ANY($2)", + workspace_id, + &ids, + ) + .fetch_all(db) + .await?; + let mut finished = Vec::with_capacity(completed.len()); + for (id, success, result) in completed.into_iter().map(|c| (c.id, c.success, c.result)) { + let Some(index) = running.iter().position(|b| b.job_id == id) else { + continue; + }; + let job = running.remove(index); + let result = result + .map(|r| r.0) + .unwrap_or_else(|| to_raw_value(&serde_json::Value::Null)); + let content = if job.is_agent && success { + extract_ai_agent_output(&result).unwrap_or_else(|| result.get().to_string()) + } else { + result.get().to_string() + }; + finished.push(FinishedBackgroundJob { job, success, content }); + } + // Call order, so a run reads the same however the completions raced. + finished.sort_by_key(|f| f.job.action_index); + Ok(finished) +} + +async fn start_background_tool( + ctx: &mut ToolExecutionContext<'_>, + tool_call: &OpenAIToolCall, + tool: &Tool, + actions: &mut Vec<AgentAction>, + messages: &mut Vec<OpenAIMessage>, +) -> Result<BackgroundJob, Error> { + let job_id = ulid::Ulid::new().into(); + // Never reserved for this worker: it is busy with the agent, which may park before the job + // is pulled. + enqueue_windmill_tool(ctx, tool_call, tool, actions, job_id, false).await?; + let action_index = actions.len() - 1; + let content = format!( + "Started in the background as job {job_id}. Its result arrives in a later message: keep \ + working meanwhile, or finish your answer and you will continue once it is in." + ); + let row = format!("Started {} in the background", tool_call.function.name); + answer_in_background( + ctx, + tool_call, + tool, + actions, + messages, + job_id, + action_index, + content, + row, + ) + .await +} + +/// Answer a call whose job keeps running, and hand the job to the agent's background list. +async fn answer_in_background( + ctx: &mut ToolExecutionContext<'_>, + tool_call: &OpenAIToolCall, + tool: &Tool, + actions: &[AgentAction], + messages: &mut Vec<OpenAIMessage>, + job_id: Uuid, + action_index: usize, + content: String, + row: String, +) -> Result<BackgroundJob, Error> { + if let Some(parent_job) = ctx.parent_job { + set_flow_status_module_action_success_at(ctx.db, parent_job, action_index, None).await?; + } + messages.push(OpenAIMessage { + role: "tool".to_string(), + content: Some(OpenAIContent::Text(content.clone())), + tool_call_id: Some(tool_call.id.clone()), + agent_action: actions.get(action_index).cloned(), + ..Default::default() + }); + let extras = MessageExtras { + tool_arguments: Some(tool_call.function.arguments.clone()), + tool_result: Some(content), + ..Default::default() + }; + add_tool_message_to_chat(ctx, Some(job_id), &row, true, Some(extras)).await; + Ok(BackgroundJob { + call_id: tool_call.id.clone(), + function_name: tool_call.function.name.clone(), + arguments: tool_call.function.arguments.clone(), + module_id: tool + .module + .as_ref() + .map(|m| m.id.clone()) + .unwrap_or_default(), + job_id, + action_index, + is_agent: tool.module.as_ref().is_some_and(|module| { + matches!( + module.get_value(), + Ok(FlowModuleValue::AIAgent { .. } | FlowModuleValue::AIDecision { .. }) + ) + }), + adopted: false, + }) } pub enum ApprovalGate<'a> { @@ -514,6 +733,7 @@ async fn enqueue_windmill_tool( tool_call: &OpenAIToolCall, tool: &Tool, actions: &mut Vec<AgentAction>, + job_id: Uuid, reserved: bool, ) -> Result<(Uuid, bool), Error> { // Regular Windmill tools must have a module @@ -521,7 +741,6 @@ async fn enqueue_windmill_tool( Error::internal_err(format!("Tool {} has no module", tool_call.function.name)) })?; - let job_id = ulid::Ulid::new().into(); actions.push(AgentAction::ToolCall { job_id, function_name: tool_call.function.name.clone(), @@ -969,9 +1188,14 @@ async fn execute_windmill_tools( batch: &[(&OpenAIToolCall, &Tool)], actions: &mut Vec<AgentAction>, messages: &mut Vec<OpenAIMessage>, + started: &mut Vec<BackgroundJob>, final_events_str: &mut String, ) -> Result<(), Error> { let mut job_ids = Vec::with_capacity(batch.len()); + let mut action_indexes = Vec::with_capacity(batch.len()); + // When a call still running is answered as a background one. Such a job never runs in this + // worker's process, which could not release the worker while it runs: the agent may park. + let mut detach_at = Vec::with_capacity(batch.len()); let mut local = None; for (index, (call, tool)) in batch.iter().enumerate() { if index > 0 { @@ -987,8 +1211,21 @@ async fn execute_windmill_tools( .await?; } } - let (id, reserved) = enqueue_windmill_tool(ctx, call, tool, actions, index == 0).await?; + let job_id = ulid::Ulid::new().into(); + let detach_after = tool.background_after_secs; + let (id, reserved) = enqueue_windmill_tool( + ctx, + call, + tool, + actions, + job_id, + index == 0 && detach_after.is_none(), + ) + .await?; job_ids.push(id); + action_indexes.push(actions.len() - 1); + detach_at + .push(detach_after.map(|secs| Instant::now() + Duration::from_secs(u64::from(secs)))); if reserved { let job = get_mini_pulled_job(ctx.db, &id) .await? @@ -1020,7 +1257,7 @@ async fn execute_windmill_tools( .collect(); if !pending.is_empty() { let completed = sqlx::query!( - "SELECT id, status = 'success' AS \"success!\", result AS \"result: Json<Box<RawValue>>\" + "SELECT id, status IN ('success', 'skipped') AS \"success!\", result AS \"result: Json<Box<RawValue>>\" FROM v2_job_completed WHERE workspace_id = $1 AND id = ANY($2)", ctx.job.workspace_id, &pending, @@ -1067,10 +1304,39 @@ async fn execute_windmill_tools( // Transcript rows, model messages, and positional action statuses share call order. while next_result < batch.len() { let job_id = job_ids[next_result]; - let Some((success, content)) = results.remove(&job_id) else { - break; - }; let (call, tool) = batch[next_result]; + let Some((success, content)) = results.remove(&job_id) else { + if !detach_at[next_result].is_some_and(|at| Instant::now() >= at) { + break; + } + let secs = tool.background_after_secs.unwrap_or_default(); + let content = format!( + "Not finished after {secs}s, so it continues in the background as job \ + {job_id}. Its result arrives in a later message: keep working meanwhile, or \ + finish your answer and you will continue once it is in." + ); + let row = format!( + "Moved {} to the background after {secs}s", + call.function.name + ); + let action_index = action_indexes[next_result]; + started.push( + answer_in_background( + ctx, + call, + tool, + actions, + messages, + job_id, + action_index, + content, + row, + ) + .await?, + ); + next_result += 1; + continue; + }; let module = tool .module .as_ref() @@ -1095,10 +1361,9 @@ async fn execute_windmill_tools( } if local.is_none() && next_result < batch.len() { - let pending: Vec<Uuid> = job_ids[next_result..] - .iter() - .filter(|id| !results.contains_key(id)) - .copied() + let pending: Vec<Uuid> = (next_result..batch.len()) + .filter(|&i| detach_at[i].is_none() && !results.contains_key(&job_ids[i])) + .map(|i| job_ids[i]) .collect(); if !pending.is_empty() { local = claim_local_tool(ctx, &pending).await?; @@ -1195,14 +1460,14 @@ async fn add_tool_message_to_chat( let chat_enabled = ctx .flow_context - .flow_status + .run_status .as_ref() .and_then(|fs| fs.chat_input_enabled) .unwrap_or(false); if chat_enabled { if let Some(memory_id) = ctx .flow_context - .flow_status + .run_status .as_ref() .and_then(|fs| fs.memory_id) { @@ -1292,6 +1557,7 @@ mod tests { mcp_source: None, requires_approval, question_timeout_secs: question.then_some(60), + background_after_secs: None, }; let call = |id: &str, name: &str| OpenAIToolCall { id: id.to_string(), diff --git a/backend/windmill-worker/src/ai/utils.rs b/backend/windmill-worker/src/ai/utils.rs index 084b3cfe04..387d37d7ac 100644 --- a/backend/windmill-worker/src/ai/utils.rs +++ b/backend/windmill-worker/src/ai/utils.rs @@ -14,7 +14,7 @@ use windmill_common::{ db::DB, error::Error, flow_conversations::{add_message_to_conversation_tx, MessageExtras, MessageType}, - flow_status::AgentAction, + flow_status::{AgentAction, FlowStatus}, flows::{InputTransform, Step}, jobs::JobKind, scripts::{ScriptHash, ScriptLang}, @@ -141,47 +141,56 @@ pub async fn get_flow_job_runnable_and_raw_flow( #[derive(Debug, Clone, Default)] pub struct FlowContext { + /// `flow_input` of the flow running the step. pub flow_inputs: Option<HashMap<String, Box<RawValue>>>, - pub flow_status: Option<windmill_common::flow_status::FlowStatus>, + /// Status of the flow running the step, which `results.<step>` and the previous result read. + pub step_flow_status: Option<FlowStatus>, + /// Status of the root run, which holds the chat settings and the run's memory id. + pub run_status: Option<FlowStatus>, /// Path of the flow the run started from, which scopes a string memory id. pub flow_path: Option<String>, + /// The root run, whose user state `flow_user_state` reads. + pub root_job_id: Option<Uuid>, } -/// Get flow context (chat settings + args + flow_status) from root flow's job data -pub async fn get_flow_context(db: &DB, job: &MiniPulledJob) -> FlowContext { - let root_job_id = job - .root_job - .or(job.flow_innermost_root_job) - .or(job.parent_job); - - let Some(root_job_id) = root_job_id else { - return FlowContext::default(); - }; - +/// Read the context an agent step evaluates its tools in. `flow_input` and `results` are those of +/// `flow_job_id`, the flow the agent is a step of, as for any other step: inside a subflow that is +/// not the root run. Chat and memory belong to the whole run. +/// +/// The root is resolved from the flow job, as `get_root_job_id` does: a nested agent's own +/// `root_job` names the agent calling it, which has no status row. +pub async fn get_flow_context(db: &DB, job: &MiniPulledJob, flow_job_id: &Uuid) -> FlowContext { match sqlx::query!( r#" SELECT - j.args as "args: Json<HashMap<String, Box<RawValue>>>", - js.flow_status as "flow_status: Json<windmill_common::flow_status::FlowStatus>", - j.runnable_path - FROM v2_job_status js - INNER JOIN v2_job j ON j.id = js.id - WHERE js.id = $1 + f.args as "args: Json<HashMap<String, Box<RawValue>>>", + fs.flow_status as "step_flow_status: Json<FlowStatus>", + rs.flow_status as "run_status: Json<FlowStatus>", + r.runnable_path, + r.id as root_job_id + FROM v2_job f + LEFT JOIN v2_job_status fs ON fs.id = f.id + INNER JOIN v2_job r + ON r.id = COALESCE(f.root_job, f.flow_innermost_root_job, f.parent_job, f.id) + LEFT JOIN v2_job_status rs ON rs.id = r.id + WHERE f.id = $1 "#, - root_job_id + flow_job_id ) .fetch_optional(db) .await { Ok(Some(row)) => FlowContext { flow_inputs: row.args.map(|j| j.0), - flow_status: row.flow_status.map(|j| j.0), + step_flow_status: row.step_flow_status.map(|j| j.0), + run_status: row.run_status.map(|j| j.0), flow_path: row.runnable_path, + root_job_id: Some(row.root_job_id), }, Ok(None) => { tracing::warn!( - "No flow context found for root job {} (agent job {}), returning default", - root_job_id, + "No flow context found for flow job {} (agent job {}), returning default", + flow_job_id, job.id ); FlowContext::default() @@ -307,34 +316,100 @@ pub async fn update_flow_status_module_with_actions_success( Ok(()) } -/// Record the outcome of the last of `action_count` actions, dropping any recorded past it. -pub async fn set_flow_status_module_last_action_success( +/// Record the outcome of the action at `index`, `None` while it runs. Outcomes are positional and +/// a background call's comes after later actions' own, so it is set in place, padded with nulls. +pub async fn set_flow_status_module_action_success_at( db: &DB, parent_job: &Uuid, - action_count: usize, - action_success: bool, + index: usize, + action_success: Option<bool>, ) -> Result<(), Error> { if let Step::Step { idx: step, .. } = get_step_of_flow_status(db, parent_job.to_owned()).await? { - sqlx::query( + sqlx::query!( "UPDATE v2_job_status SET flow_status = jsonb_set( flow_status, - array['modules', $2::TEXT, 'agent_actions_success'], + array['modules', $2::int::TEXT, 'agent_actions_success'], + ( + SELECT jsonb_agg(CASE WHEN i = $3 THEN to_jsonb($4::bool) ELSE arr->i END ORDER BY i) + FROM (SELECT COALESCE( + flow_status->'modules'->$2::int->'agent_actions_success', '[]'::jsonb + ) AS arr) a, + generate_series(0, GREATEST(jsonb_array_length(arr) - 1, $3)) AS i + ) + ) + WHERE id = $1", + parent_job, + step as i32, + index as i32, + action_success + ) + .execute(db) + .await?; + } + Ok(()) +} + +/// Mark as failed the outcomes still `null`: background calls whose agent ended before they did, +/// and whose jobs it cancels. +pub async fn fail_unfinished_action_successes(db: &DB, parent_job: &Uuid) -> Result<(), Error> { + if let Step::Step { idx: step, .. } = get_step_of_flow_status(db, parent_job.to_owned()).await? + { + sqlx::query!( + "UPDATE v2_job_status SET + flow_status = jsonb_set( + flow_status, + array['modules', $2::int::TEXT, 'agent_actions_success'], + ( + SELECT jsonb_agg(CASE WHEN e = 'null'::jsonb THEN 'false'::jsonb ELSE e END + ORDER BY i) + FROM jsonb_array_elements( + flow_status->'modules'->$2::int->'agent_actions_success' + ) WITH ORDINALITY AS t(e, i) + ) + ) + WHERE id = $1 + AND flow_status->'modules'->$2::int->'agent_actions_success' @> '[null]'::jsonb", + parent_job, + step as i32 + ) + .execute(db) + .await?; + } + Ok(()) +} + +/// Keep the first `keep` action outcomes, dropping any recorded past them, then append `append`. +/// A resumed segment calls it so that one replayed after its worker died records nothing twice. +pub async fn reset_flow_status_module_action_successes( + db: &DB, + parent_job: &Uuid, + keep: usize, + append: Option<bool>, +) -> Result<(), Error> { + if let Step::Step { idx: step, .. } = get_step_of_flow_status(db, parent_job.to_owned()).await? + { + sqlx::query!( + "UPDATE v2_job_status SET + flow_status = jsonb_set( + flow_status, + array['modules', $2::int::TEXT, 'agent_actions_success'], COALESCE(( SELECT jsonb_agg(e ORDER BY i) FROM jsonb_array_elements( - flow_status->'modules'->$2->'agent_actions_success' + flow_status->'modules'->$2::int->'agent_actions_success' ) WITH ORDINALITY AS t(e, i) - WHERE i < $3 - ), '[]'::jsonb) || to_jsonb(ARRAY[$4::bool]) + WHERE i <= $3 + ), '[]'::jsonb) || CASE WHEN $4::bool IS NULL THEN '[]'::jsonb + ELSE to_jsonb(ARRAY[$4::bool]) END ) WHERE id = $1", + parent_job, + step as i32, + keep as i64, + append ) - .bind(parent_job) - .bind(step as i32) - .bind(action_count as i64) - .bind(action_success) .execute(db) .await?; } @@ -441,6 +516,7 @@ fn convert_mcp_tools_to_windmill_tools( }), requires_approval: false, question_timeout_secs: None, + background_after_secs: None, }) }) .collect() diff --git a/backend/windmill-worker/src/ai_executor.rs b/backend/windmill-worker/src/ai_executor.rs index 385f88685c..2f72794753 100644 --- a/backend/windmill-worker/src/ai_executor.rs +++ b/backend/windmill-worker/src/ai_executor.rs @@ -3,18 +3,21 @@ use crate::ai::compaction::{ Compactor, }; use crate::ai::pause::{ - answer_pause, load_checkpoint, park, question_timeout, question_tool, AgentCheckpoint, Answer, - ParkOutcome, PendingRequest, Resumed, QUESTION_ENABLED_NAME, + answer_pause, dropped_answer, dropped_messages, load_checkpoint, park, question_timeout, + question_tool, resume_without_approval, AgentCheckpoint, Answer, ParkOutcome, PendingRequest, + Resumed, QUESTION_ENABLED_NAME, }; use crate::ai::tools::{ - execute_tool_calls, ApprovalGate, ToolAbortHandles, ToolCallsOutcome, ToolExecutionContext, + execute_tool_calls, take_finished_background_jobs, ApprovalGate, BackgroundJob, + ToolAbortHandles, ToolCallsOutcome, ToolExecutionContext, }; use crate::ai::utils::{ add_message_to_conversation, any_tool_needs_previous_result, cleanup_mcp_clients, - filter_schema_by_input_transforms, find_unique_tool_name, get_flow_context, - get_flow_job_runnable_and_raw_flow, get_step_name_from_flow, load_mcp_tools, - parse_raw_script_schema, set_flow_status_module_last_action_success, - update_flow_status_module_with_actions, update_flow_status_module_with_actions_success, + fail_unfinished_action_successes, filter_schema_by_input_transforms, find_unique_tool_name, + get_flow_context, get_flow_job_runnable_and_raw_flow, get_step_name_from_flow, load_mcp_tools, + parse_raw_script_schema, reset_flow_status_module_action_successes, + set_flow_status_module_action_success_at, update_flow_status_module_with_actions, + update_flow_status_module_with_actions_success, }; use crate::memory_common::MAX_MEMORY_SIZE_BYTES; use crate::memory_oss::{memory_storage_capacity_bytes, read_from_memory, write_to_memory}; @@ -428,7 +431,7 @@ fn note_unread_step_inputs(notes: &mut Vec<&'static str>, args: &AIAgentArgs) { /// an image prompt comes from the user message alone. An empty list is no conversation, except /// under a legacy `manual` memory, which ran on whatever list it held. fn has_prompt( - history: &HistorySource, + history: &HistorySource<'_>, has_user_message: bool, is_text_output: bool, legacy_list: bool, @@ -978,6 +981,8 @@ pub async fn handle_ai_agent_job( // Explicit per-tool descriptions keyed by tool id. When set, these override the // description auto-derived from the underlying runnable when building tool definitions. let mut tool_descriptions: HashMap<String, String> = HashMap::new(); + // A nested agent cannot park to wait for one, so its background tools run like any other. + let mut background_tools: HashMap<String, u32> = HashMap::new(); #[allow(unused_mut)] let mut mcp_configs: Vec<crate::ai::utils::McpResourceConfig> = Vec::new(); let mut has_websearch = false; @@ -1027,6 +1032,16 @@ pub async fn handle_ai_agent_job( { tool_descriptions.insert(tool.id.clone(), description.to_string()); } + let background_after_secs = if tool.background { + Some(0) + } else { + tool.background_after_secs + }; + if let Some(secs) = background_after_secs { + if direct_parent_job_kind != JobKind::AIAgent { + background_tools.insert(tool.id.clone(), secs); + } + } if let Some(flow_module) = Option::<FlowModule>::from(&tool) { windmill_modules.push(flow_module); } @@ -1049,6 +1064,7 @@ pub async fn handle_ai_agent_job( let job = job; let user_description = tool_descriptions.get(&t.id).cloned(); let requires_approval = approval_required.contains(&t.id); + let background_after_secs = background_tools.get(&t.id).copied(); async move { let summary = flow_module_tool_name(t.summary.as_deref())?; @@ -1184,6 +1200,7 @@ pub async fn handle_ai_agent_job( module: Some(t), mcp_source: None, question_timeout_secs: None, + background_after_secs, }) } })) @@ -1253,6 +1270,7 @@ pub async fn handle_ai_agent_job( db, conn, job, + &flow_job_id, flow_status_job.as_ref(), Some(flow_step_id.as_str()), &args, @@ -1268,7 +1286,9 @@ pub async fn handle_ai_agent_job( killpill_rx, has_stream, has_websearch, - omit_output_from_conversation, + // A nested agent answers its caller, whose tool message carries that answer into the + // chat; its own rows would also be tied to the calling agent's job, not the turn. + omit_output_from_conversation || direct_parent_job_kind == JobKind::AIAgent, preserve_step_tags, cancel_rx, tool_abort_handles.clone(), @@ -1341,24 +1361,243 @@ pub async fn handle_ai_agent_job( handle.abort(); } cleanup_orphaned_tool_jobs(db, &job.id, &job.workspace_id, canceled_by.clone()).await; + if let Some(parent_job) = flow_status_job.as_ref() { + if let Err(e) = fail_unfinished_action_successes(db, parent_job).await { + tracing::error!("Failed to close the background calls of {}: {e}", job.id); + } + } } cleanup_mcp_clients(mcp_clients).await; result } -/// Park the agent on its pending approval, as the error `run_agent` returns. +/// Say in the job's logs when storage capacity cut what memory keeps. +async fn log_memory_fit( + conn: &Connection, + job: &MiniPulledJob, + memory_to_save: Option<&[OpenAIMessage]>, + held: usize, +) { + if memory_to_save.is_some_and(|tail| tail.len() < held) { + append_logs(&job.id, &job.workspace_id, + "AI agent memory exceeds storage capacity; saving only the newest complete exchanges. Older memory was dropped; the answer and run action results are preserved.\n".to_string(), conn).await; + } else if memory_to_save.is_none() { + append_logs(&job.id, &job.workspace_id, + "AI agent memory has no complete user-starting conversation that fits storage capacity and memory was not saved. The answer is preserved; the next run will load the previous saved memory.\n".to_string(), conn).await; + } +} + +/// Write `memory_to_save` to the step's managed memory, if it keeps one. +async fn persist_memory( + db: &DB, + conn: &Connection, + job: &MiniPulledJob, + history: &HistorySource<'_>, + effective_flow_step_id: Option<&str>, + memory_to_save: &[OpenAIMessage], +) { + if let HistorySource::Managed { memory_id, bound } = history { + if let Some(step_id) = effective_flow_step_id { + if !memory_to_save.is_empty() { + let messages_to_persist = prepare_auto_memory_messages_for_persistence( + memory_to_save, + bound.messages_to_keep(), + ); + + match write_to_memory( + db, + &job.workspace_id, + *memory_id, + step_id, + &messages_to_persist, + matches!(bound, MemoryBound::LastMessages(_)), + ) + .await + { + // The conversation outgrew what the database holds and was cut + // from its oldest message. Only the worker's own log says so + // otherwise, so from the flow's side the agent simply starts the + // next run having forgotten how this one began. + Ok(dropped) if dropped > 0 => { + append_logs( + &job.id, + &job.workspace_id, + format!( + "Memory does not fit the {}KB the database holds, so its \ + {dropped} oldest messages were dropped. Configure instance \ + object storage to keep the whole conversation.\n", + MAX_MEMORY_SIZE_BYTES / 1000 + ), + conn, + ) + .await; + } + Ok(_) => {} + Err(e) => { + tracing::error!( + "Failed to persist {} messages to memory for step {}: {}", + messages_to_persist.len(), + step_id, + e + ); + append_logs(&job.id, &job.workspace_id, + "Agent memory could not be saved. The answer is preserved; the next run may load older memory.\n".to_string(), conn).await; + } + } + } + } + } +} + +/// A stopped turn keeps what it reached instead of losing the whole exchange: every place it +/// stops at has each tool call answered. No compaction runs here, since it would call the model +/// while the cancel waits. +async fn persist_memory_on_stop( + db: &DB, + conn: &Connection, + job: &MiniPulledJob, + history: &HistorySource<'_>, + effective_flow_step_id: Option<&str>, + output_type: &OutputType, + persist_capacity: Option<usize>, + handed_over: bool, + messages: &AgentHistory, +) -> Error { + // A turn taken over leaves the memory to the run that took it. + if handed_over { + return Error::ExecutionErr("Job cancelled".to_string()); + } + persist_memory_uncompacted( + db, + conn, + job, + history, + effective_flow_step_id, + output_type, + persist_capacity, + messages.context(), + ) + .await; + Error::ExecutionErr("Job cancelled".to_string()) +} + +/// A parked turn saves its conversation, so that a new run of the same memory id taking it over +/// reads it. An open request's calls read as dropped, which is what they become then. A turn that +/// resumes instead saves again when it ends. +async fn persist_memory_at_park( + db: &DB, + conn: &Connection, + job: &MiniPulledJob, + history: &HistorySource<'_>, + effective_flow_step_id: Option<&str>, + output_type: &OutputType, + persist_capacity: Option<usize>, + checkpoint: &AgentCheckpoint, + messages: &AgentHistory, +) { + let mut context = messages.context().to_vec(); + if let Some(pending) = &checkpoint.pending { + context.extend(dropped_messages(pending, &checkpoint.actions)); + } + persist_memory_uncompacted( + db, + conn, + job, + history, + effective_flow_step_id, + output_type, + persist_capacity, + &context, + ) + .await; +} + +async fn persist_memory_uncompacted( + db: &DB, + conn: &Connection, + job: &MiniPulledJob, + history: &HistorySource<'_>, + effective_flow_step_id: Option<&str>, + output_type: &OutputType, + persist_capacity: Option<usize>, + context: &[OpenAIMessage], +) { + if matches!(output_type, OutputType::Text) { + let memory_to_save = match persist_capacity { + Some(limit) => memory_within_capacity(context, limit), + None => Some(context), + }; + log_memory_fit(conn, job, memory_to_save, context.len()).await; + if let Some(memory_to_save) = memory_to_save { + persist_memory( + db, + conn, + job, + history, + effective_flow_step_id, + memory_to_save, + ) + .await; + } + } +} + +/// The background jobs of a parked turn this run took over, for this step's agent to wait on. +async fn adopt_handed_jobs( + db: &DB, + job: &MiniPulledJob, + memory_id: Uuid, + step_id: &str, +) -> error::Result<Vec<BackgroundJob>> { + let jobs = sqlx::query_scalar!( + r#"UPDATE ai_memory_turn t SET handed_jobs = t.handed_jobs - $4::text + FROM (SELECT handed_jobs -> $4::text AS jobs FROM ai_memory_turn + WHERE workspace_id = $1 AND memory_id = $2 AND job_id = $3) old + WHERE t.workspace_id = $1 AND t.memory_id = $2 AND t.job_id = $3 + AND t.handed_jobs ? $4::text + RETURNING old.jobs AS "jobs: sqlx::types::Json<Vec<BackgroundJob>>""#, + &job.workspace_id, + memory_id, + get_root_job_id(job), + step_id + ) + .fetch_optional(db) + .await? + .flatten(); + let mut jobs = jobs.map(|j| j.0).unwrap_or_default(); + for adopted in &mut jobs { + adopted.adopted = true; + } + // Under this agent, as the jobs it starts are: its cancel and its cleanup walk its children. + let ids: Vec<Uuid> = jobs.iter().map(|j| j.job_id).collect(); + if !ids.is_empty() { + sqlx::query!( + "UPDATE v2_job SET parent_job = $2, root_job = $3, flow_innermost_root_job = $4 + WHERE id = ANY($1) AND workspace_id = $5", + &ids, + job.id, + get_root_job_id(job), + job.flow_innermost_root_job.unwrap_or(job.id), + &job.workspace_id + ) + .execute(db) + .await?; + } + Ok(jobs) +} + +/// Park the agent, as the error `run_agent` returns. `None` when a background job finished +/// before the park was written, so the agent goes on instead; never for a park on an approval. async fn park_agent( db: &DB, conn: &Connection, job: &MiniPulledJob, checkpoint: &AgentCheckpoint, cancel_rx: &tokio::sync::watch::Receiver<bool>, -) -> Error { - match park(db, conn, job, checkpoint).await { - Ok(ParkOutcome::Parked) => Error::WacSuspended(format!( - "AI agent {} parked on {}", - job.id, checkpoint.pending.call_id - )), +) -> Option<Error> { + Some(match park(db, conn, job, checkpoint).await { + Ok(ParkOutcome::JobFinished) => return None, + Ok(ParkOutcome::Parked) => Error::WacSuspended(format!("AI agent {} parked", job.id)), Ok(ParkOutcome::Cancelled) => { // The cancel is on the queue row but not yet seen by the poller, which is what // completes the job as cancelled rather than failed. Wait for it to notice. @@ -1371,7 +1610,12 @@ async fn park_agent( Error::ExecutionErr("Job cancelled".to_string()) } Err(e) => e, - } + }) +} + +/// A park on an approval is never stood down by a background job. +fn approval_park(parked: Option<Error>) -> Error { + parked.unwrap_or_else(|| Error::internal_err("AI agent approval park was skipped".to_string())) } /// OpenAI rejects a `prompt_cache_key` over 64 characters @@ -1400,6 +1644,8 @@ pub async fn run_agent( // agent job and flow data job: &MiniPulledJob, + // the flow the agent is a step of, past the calling agent for a nested agent tool + flow_job_id: &Uuid, parent_job: Option<&Uuid>, flow_step_id_override: Option<&str>, args: &AIAgentArgs, @@ -1478,35 +1724,54 @@ pub async fn run_agent( )); // Fetch flow context for input transforms context, chat and memory - let mut flow_context = get_flow_context(db, job).await; - // Set when the job parked on an approval or a question and has been pulled again. Read + let mut flow_context = get_flow_context(db, job, flow_job_id).await; + // Set when the job parked on a request or on background jobs and has been pulled again. Read // whatever the roster says now: a linked agent can lose a tool while one of its runs is parked. let resumed = match load_checkpoint(db, &job.id).await? { + Some(mut checkpoint) if checkpoint.handed_over => { + resume_without_approval(db, &job.id, &mut checkpoint.consumed_resume_rows).await?; + // Nothing is left to ask the model: the new run carries the conversation on. + checkpoint.background.clear(); + checkpoint.answered = true; + let answer = checkpoint.pending.clone().map(|pending| { + let answer = dropped_answer(&pending, &checkpoint.actions); + (pending, answer, false) + }); + Some((checkpoint, answer)) + } Some(mut checkpoint) => { - let answer = answer_pause( - db, - &job.id, - &checkpoint.pending, - &checkpoint.actions, - &mut checkpoint.consumed_resume_rows, - ) - .await?; - match answer { - Resumed::StillPending => { - return Err(park_agent(db, conn, job, &checkpoint, &cancel_rx).await) + let answer = match checkpoint.pending.clone() { + Some(pending) => { + let answer = answer_pause( + db, + &job.id, + &pending, + &checkpoint.actions, + &mut checkpoint.consumed_resume_rows, + ) + .await?; + match answer { + Resumed::StillPending => { + let parked = park_agent(db, conn, job, &checkpoint, &cancel_rx).await; + return Err(approval_park(parked)); + } + Resumed::Answered(message, success) => Some((pending, message, success)), + } } - Resumed::Answered(message, success) => Some((checkpoint, message, success)), - } + None => { + resume_without_approval(db, &job.id, &mut checkpoint.consumed_resume_rows) + .await?; + None + } + }; + Some((checkpoint, answer)) } None => None, }; // The run's memory id is also the chat conversation id, which a step's own memory id never // replaces. - let conversation_id = flow_context - .flow_status - .as_ref() - .and_then(|fs| fs.memory_id); + let conversation_id = flow_context.run_status.as_ref().and_then(|fs| fs.memory_id); let (history, history_notes) = resolve_history_source( args, conversation_id, @@ -1584,11 +1849,20 @@ pub async fn run_agent( // Extract previous step result only if any tool needs it let previous_result = { if any_tool_needs_previous_result(&tools) { - if let Some(ref flow_status) = flow_context.flow_status { - get_previous_job_result(db, &job.workspace_id, flow_status) - .await - .ok() - .flatten() + if let Some(ref flow_status) = flow_context.step_flow_status { + // As for a regular step, the first step of a flow (a subflow, a loop iteration) + // gets that flow's args: no step precedes it. + if flow_status.step == 0 { + flow_context + .flow_inputs + .as_ref() + .and_then(|args| serde_json::value::to_raw_value(args).ok()) + } else { + get_previous_job_result(db, &job.workspace_id, flow_status) + .await + .ok() + .flatten() + } } else { None } @@ -1599,13 +1873,18 @@ pub async fn run_agent( // Build IdContext for results.stepId syntax let id_context = { - if let Some(ref flow_status) = flow_context.flow_status { + if let Some(ref flow_status) = flow_context.step_flow_status { // Get the step ID from the AI agent's flow step let previous_id = effective_flow_step_id .map(str::to_string) .unwrap_or_else(|| "unknown".to_string()); - Some(get_transform_context(job, &previous_id, flow_status)) + let mut id_context = get_transform_context(job, &previous_id, flow_status); + // The agent's own root names the calling agent for a nested agent. + if let Some(root) = flow_context.root_job_id { + id_context.root_flow_job = root; + } + Some(id_context) } else { None } @@ -1663,13 +1942,26 @@ pub async fn run_agent( let mut first_iteration = 0; let mut consumed_resume_rows = vec![]; let mut resumed_answer = None; + let mut background = vec![]; + let mut answered = false; + let mut keep_structured_answer = false; + let was_resumed = resumed.is_some(); + let handed_over = resumed.as_ref().is_some_and(|(c, _)| c.handed_over); + if let (None, Some(memory_id), Some(step_id)) = + (resumed.as_ref(), conversation_id, effective_flow_step_id) + { + background = adopt_handed_jobs(db, job, memory_id, step_id).await?; + } let (mut messages, mut actions, mut content, mut final_usage) = match resumed { - Some((checkpoint, message, success)) => { + Some((checkpoint, answer)) => { final_events_str = checkpoint.events; final_reasoning = checkpoint.reasoning; first_iteration = checkpoint.next_iteration; consumed_resume_rows = checkpoint.consumed_resume_rows; - resumed_answer = Some((checkpoint.pending, message, success)); + background = checkpoint.background; + answered = checkpoint.answered; + keep_structured_answer = checkpoint.structured_answer; + resumed_answer = answer; ( AgentHistory::from_checkpoint(checkpoint.history), checkpoint.actions, @@ -1715,7 +2007,7 @@ pub async fn run_agent( function: ToolDefFunction { name: unique_tool_name, description: Some( - "This tool MUST be used last to return a structured JSON object as the final output." + "Return the final answer. Always finish by calling this tool exactly once with the answer as its input, instead of replying in plain text." .to_string(), ), parameters: to_raw_value(&schema), @@ -1734,20 +2026,25 @@ pub async fn run_agent( *has_stream = user_wants_streaming && is_text_output; // Always create a StreamEventProcessor for text output (use silent mode if user doesn't want streaming) - let mut stream_event_processor = if is_text_output { - if user_wants_streaming { - // Each streamed event is one line of the accumulated string. - let streamed = final_events_str.lines().count() as i32; - Some(StreamEventProcessor::new(conn, job, streamed)) + // Each streamed event is one line of the accumulated string, so a segment streams on from + // where the last one stopped. + let new_stream_event_processor = |events: &str| { + if !is_text_output { + None + } else if user_wants_streaming { + Some(StreamEventProcessor::new( + conn, + job, + events.lines().count() as i32, + )) } else { Some(StreamEventProcessor::new_silent()) } - } else { - None }; + let mut stream_event_processor = new_stream_event_processor(&final_events_str); let chat_enabled = flow_context - .flow_status + .run_status .as_ref() .and_then(|fs| fs.chat_input_enabled) .unwrap_or(false); @@ -1805,15 +2102,18 @@ pub async fn run_agent( let mut anthropic_federated_token: Option< windmill_ai::providers::anthropic::FederatedAccessToken, > = None; + let mut vertex_access_token: Option<windmill_ai::vertex_workload_identity::GcpAccessToken> = + None; + if let (true, Some(parent_job)) = (was_resumed, parent_job) { + // Rewritten whole rather than appended: a job restarted after its worker died resumes + // from the same checkpoint and must not record anything twice. + update_flow_status_module_with_actions(db, parent_job, &actions).await?; + let answer = resumed_answer.as_ref().map(|(_, _, success)| *success); + let keep = actions.len() - usize::from(answer.is_some()); + reset_flow_status_module_action_successes(db, parent_job, keep, answer).await?; + } if let Some((pending, answer, success)) = resumed_answer { - if let Some(parent_job) = parent_job { - // Rewritten whole rather than appended: a job restarted after its worker died - // resumes from the same checkpoint and must not record the answer twice. - update_flow_status_module_with_actions(db, parent_job, &actions).await?; - set_flow_status_module_last_action_success(db, parent_job, actions.len(), success) - .await?; - } match (pending.request, answer) { (PendingRequest::Question { function_name }, Answer::Question(message)) => { if let (Some(processor), Some(OpenAIContent::Text(result))) = @@ -1850,7 +2150,9 @@ pub async fn run_agent( killpill_rx, stream_event_processor: stream_event_processor.as_ref(), flow_context: &mut flow_context, - omit_output_from_conversation, + // Dropped for a turn that took over: in its chat, the row would land after + // that turn's message. The run's own trace keeps the refusal. + omit_output_from_conversation: omit_output_from_conversation || handed_over, preserve_step_tags, reasoning: None, previous_result: &previous_result, @@ -1870,6 +2172,7 @@ pub async fn run_agent( ) .await?; messages.extend(outcome.messages); + background.extend(outcome.started); } (PendingRequest::Question { .. }, _) => { return Err(Error::internal_err( @@ -1880,14 +2183,133 @@ pub async fn run_agent( } // Main agent loop - for i in first_iteration..max_iterations { + // Advanced by each model call that answers the run's own work; the call that follows a + // background result reuses the iteration of the answer it revisits. + let mut i = first_iteration; + while i < max_iterations { // Check if parent was canceled — stop iterating but let current tool calls finish - if *cancel_rx.borrow() { - return Err(Error::ExecutionErr("Job cancelled".to_string())); + let cancelled = *cancel_rx.borrow(); + if cancelled { + return Err(persist_memory_on_stop( + db, + conn, + job, + &history, + effective_flow_step_id, + output_type, + persist_capacity, + handed_over, + &messages, + ) + .await); } - if used_structured_output_tool { - break; + if !background.is_empty() { + let finished = + take_finished_background_jobs(db, &job.workspace_id, &mut background).await?; + if !finished.is_empty() { + answered = false; + // The model is asked again, but its structured answer stands unless it gives + // another one. + keep_structured_answer |= used_structured_output_tool; + used_structured_output_tool = false; + } + for finished in finished { + messages.push(finished.message()); + if let (false, Some(parent_job)) = (finished.job.adopted, parent_job) { + set_flow_status_module_action_success_at( + db, + parent_job, + finished.job.action_index, + Some(finished.success), + ) + .await?; + } + if let Some(processor) = stream_event_processor.as_ref() { + let event = StreamingEvent::ToolResult { + call_id: finished.job.call_id.clone(), + function_name: finished.job.function_name.clone(), + result: finished.content.clone(), + success: finished.success, + }; + processor.send(event, &mut final_events_str).await?; + } + if let (true, Some(conversation_id)) = + (persist_output_to_conversation, conversation_id) + { + let (row, extras) = finished.chat_row(); + if let Err(e) = add_message_to_conversation( + db, + &conversation_id, + Some(finished.job.job_id), + get_root_job_id(job), + &row, + MessageType::Tool, + &step_name, + finished.success, + Some(&extras), + ) + .await + { + tracing::warn!( + "Failed to add tool message to conversation {conversation_id}: {e}" + ); + } + } + } + } + + if answered || used_structured_output_tool { + if background.is_empty() { + break; + } + // The model has answered but background jobs still run: wait for one, without a + // worker. This iteration runs again, starting with what finished. + let mut checkpoint = AgentCheckpoint { + history: messages.checkpoint(), + actions: actions.clone(), + content: content.clone(), + usage: final_usage.clone(), + events: final_events_str.clone(), + reasoning: final_reasoning.clone(), + next_iteration: i, + pending: None, + background: background.clone(), + answered: true, + structured_answer: keep_structured_answer || used_structured_output_tool, + consumed_resume_rows: consumed_resume_rows.clone(), + handed_over: false, + }; + persist_memory_at_park( + db, + conn, + job, + &history, + effective_flow_step_id, + output_type, + persist_capacity, + &checkpoint, + &messages, + ) + .await; + // Told once the memory is saved, which can take a while: a client sends its next + // message over the turn on it, and the claim refuses one until the park is written. + if let Some(processor) = stream_event_processor.as_ref() { + processor + .send(StreamingEvent::BackgroundWait, &mut final_events_str) + .await?; + } + if let Some(handle) = stream_event_processor.take().and_then(|p| p.to_handle()) { + let _ = handle.await; + } + checkpoint.events = final_events_str.clone(); + match park_agent(db, conn, job, &checkpoint, &cancel_rx).await { + Some(parked) => return Err(parked), + None => { + stream_event_processor = new_stream_event_processor(&final_events_str); + continue; + } + } } compact_if_needed( @@ -2000,6 +2422,22 @@ pub async fn run_agent( ), }; + // The exchanged token stands in for the resource's api key, which + // `retain_effective_credentials` checks before keeping a credential header. + let vertex_credentials = + windmill_ai::vertex_workload_identity::refresh_vertex_access_token( + &credentials, + &mut vertex_access_token, + client, + ) + .await? + .map(|token| windmill_ai::credentials::ProviderCredentials { + api_key: Some(token.to_string()), + ..credentials.clone() + }); + let credentials = vertex_credentials.as_ref().unwrap_or(&credentials); + let api_key = credentials.api_key.as_deref().unwrap_or(api_key); + // A worker cannot run the client credentials exchange, so an OAuth resource // has no token here: the request would carry an empty credential and come // back 401. @@ -2264,11 +2702,23 @@ pub async fn run_agent( ) .await; let mut cancelled = cancel_rx.clone(); - tokio::select! { - _ = tokio::time::sleep(delay) => {} - Ok(_) = cancelled.wait_for(|cancelled| *cancelled) => { - return Err(Error::ExecutionErr("Job cancelled".to_string())); - } + let stopped = tokio::select! { + _ = tokio::time::sleep(delay) => false, + Ok(_) = cancelled.wait_for(|cancelled| *cancelled) => true, + }; + if stopped { + return Err(persist_memory_on_stop( + db, + conn, + job, + &history, + effective_flow_step_id, + output_type, + persist_capacity, + handed_over, + &messages, + ) + .await); } } } @@ -2372,7 +2822,9 @@ pub async fn run_agent( .await?; } - content = Some(OpenAIContent::Text(response_content.clone())); + if !keep_structured_answer { + content = Some(OpenAIContent::Text(response_content.clone())); + } // Add assistant message to conversation if chat_input_enabled if persist_output_to_conversation && !response_content.is_empty() { @@ -2406,7 +2858,8 @@ pub async fn run_agent( } if tool_calls.is_empty() { - break; + answered = true; + continue; } else if i == max_iterations - 1 { #[derive(serde::Serialize)] struct MaxIterError<'a> { @@ -2491,6 +2944,7 @@ pub async fn run_agent( final_content: tool_content, used_structured_output_tool: tool_used_structured_output, pause, + started, } = execute_tool_calls( tool_execution_ctx, &tool_calls, @@ -2544,6 +2998,12 @@ pub async fn run_agent( content = Some(tc); } used_structured_output_tool = tool_used_structured_output; + background.extend(started); + if used_structured_output_tool { + // An answer, like a text one: it keeps its iteration for the call that + // revisits it once a background result arrives. + continue; + } if let Some(mut pending) = pause { actions.extend(pending.action.take()); @@ -2561,10 +3021,27 @@ pub async fn run_agent( events: final_events_str, reasoning: final_reasoning, next_iteration: i + 1, - pending, + pending: Some(pending), + background, + answered: false, + structured_answer: keep_structured_answer, consumed_resume_rows, + handed_over: false, }; - let parked = park_agent(db, conn, job, &checkpoint, &cancel_rx).await; + persist_memory_at_park( + db, + conn, + job, + &history, + effective_flow_step_id, + output_type, + persist_capacity, + &checkpoint, + &messages, + ) + .await; + let parked = + approval_park(park_agent(db, conn, job, &checkpoint, &cancel_rx).await); // Written once parked: the run page offers an answer only for a request that // `resume_suspended` can take. The park is committed, so a failure here only // costs the page its banner. @@ -2582,8 +3059,20 @@ pub async fn run_agent( } // Check cancellation after tool calls complete to avoid a wasted LLM call - if *cancel_rx.borrow() { - return Err(Error::ExecutionErr("Job cancelled".to_string())); + let cancelled = *cancel_rx.borrow(); + if cancelled { + return Err(persist_memory_on_stop( + db, + conn, + job, + &history, + effective_flow_step_id, + output_type, + persist_capacity, + handed_over, + &messages, + ) + .await); } } ParsedResponse::Image { base64_data } => { @@ -2632,8 +3121,20 @@ pub async fn run_agent( return Ok(content); } } + i += 1; } + if !background.is_empty() { + // Resumed past its iteration limit, which a linked agent edited while parked can lower: + // nothing would read the background jobs' results. + cleanup_orphaned_tool_jobs(db, &job.id, &job.workspace_id, None).await; + if let Some(parent_job) = parent_job { + fail_unfinished_action_successes(db, parent_job).await?; + } + } + + // A turn taken over leaves the memory to the run that took it, which saved it at park. + let persist_capacity = persist_capacity.filter(|_| !handed_over); if let Some(capacity_bytes) = persist_capacity.filter(|limit| persisted_bytes(messages.context()) > *limit) { @@ -2659,13 +3160,7 @@ pub async fn run_agent( Some(limit) => memory_within_capacity(messages.context(), limit), None => Some(messages.context()), }; - if memory_to_save.is_some_and(|tail| tail.len() < messages.context().len()) { - append_logs(&job.id, &job.workspace_id, - "AI agent memory exceeds storage capacity after compaction; saving only the newest complete exchanges. Older memory was dropped; the answer and run action results are preserved.\n".to_string(), conn).await; - } else if memory_to_save.is_none() { - append_logs(&job.id, &job.workspace_id, - "AI agent memory has no complete user-starting conversation that fits storage capacity and memory was not saved. The answer is preserved; the next run will load the previous saved memory.\n".to_string(), conn).await; - } + log_memory_fit(conn, job, memory_to_save, messages.context().len()).await; // Return the final result let final_messages: Vec<Message> = messages @@ -2712,59 +3207,18 @@ pub async fn run_agent( } // Storage limits affect only the saved suffix, never the returned execution history. - if let Some(memory_to_save) = memory_to_save.filter(|_| matches!(output_type, OutputType::Text)) + if let Some(memory_to_save) = + memory_to_save.filter(|_| matches!(output_type, OutputType::Text) && !handed_over) { - if let HistorySource::Managed { memory_id, bound } = &history { - if let Some(step_id) = effective_flow_step_id { - if !memory_to_save.is_empty() { - let messages_to_persist = prepare_auto_memory_messages_for_persistence( - memory_to_save, - bound.messages_to_keep(), - ); - - match write_to_memory( - db, - &job.workspace_id, - *memory_id, - step_id, - &messages_to_persist, - matches!(bound, MemoryBound::LastMessages(_)), - ) - .await - { - // The conversation outgrew what the database holds and was cut - // from its oldest message. Only the worker's own log says so - // otherwise, so from the flow's side the agent simply starts the - // next run having forgotten how this one began. - Ok(dropped) if dropped > 0 => { - append_logs( - &job.id, - &job.workspace_id, - format!( - "Memory does not fit the {}KB the database holds, so its \ - {dropped} oldest messages were dropped. Configure instance \ - object storage to keep the whole conversation.\n", - MAX_MEMORY_SIZE_BYTES / 1000 - ), - conn, - ) - .await; - } - Ok(_) => {} - Err(e) => { - tracing::error!( - "Failed to persist {} messages to memory for step {}: {}", - messages_to_persist.len(), - step_id, - e - ); - append_logs(&job.id, &job.workspace_id, - "Agent memory could not be saved. The answer is preserved; the next run may load older memory.\n".to_string(), conn).await; - } - } - } - } - } + persist_memory( + db, + conn, + job, + &history, + effective_flow_step_id, + memory_to_save, + ) + .await; } Ok(to_raw_value(&AIAgentResult { @@ -2801,7 +3255,7 @@ async fn handle_ai_decision( let args = serde_json::from_str::<AIDecisionArgs>(&serde_json::to_string(local_args)?)?; if !args.provider.kind.runs_decisions() { return Err(Error::BadRequest(format!( - "An AI decision runs on a TypeSafe, Cloudflare or OpenAI resource, not {:?}", + "An AI decision runs on a TypeSafe, Cloudflare, OpenAI or Google AI resource, not {:?}", args.provider.kind ))); } @@ -3319,6 +3773,8 @@ mod tests { AgentTool { job_token_scopes: None, requires_approval: false, + background: false, + background_after_secs: None, id: id.to_string(), summary: None, description: None, @@ -3348,6 +3804,8 @@ mod tests { AgentTool { job_token_scopes: None, requires_approval: false, + background: false, + background_after_secs: None, id: "m".to_string(), summary: None, description: None, @@ -3397,6 +3855,8 @@ mod tests { AgentTool { job_token_scopes: None, requires_approval: false, + background: false, + background_after_secs: None, id: id.to_string(), summary: Some(summary.to_string()), description: None, @@ -3414,6 +3874,8 @@ mod tests { AgentTool { job_token_scopes: None, requires_approval: false, + background: false, + background_after_secs: None, id: id.to_string(), summary: Some(summary.to_string()), description: None, @@ -3428,6 +3890,8 @@ mod tests { AgentTool { job_token_scopes: None, requires_approval: false, + background: false, + background_after_secs: None, id: id.to_string(), summary: summary.map(str::to_string), description: None, diff --git a/backend/windmill-worker/src/bun_executor.rs b/backend/windmill-worker/src/bun_executor.rs index 4aa4675e12..f463dad24f 100644 --- a/backend/windmill-worker/src/bun_executor.rs +++ b/backend/windmill-worker/src/bun_executor.rs @@ -257,6 +257,22 @@ BigInt.prototype.toJSON = function () {{ return this.toString(); }}; +// `step_id`, `job_id` and `flow_path` are per job, so the worker adds them, not this process. +function errorJson(e) {{ + const err = {{ message: e.message, name: e.name, stack: e.stack }}; + const extra = {{}}; + Object.getOwnPropertyNames(e).forEach((key) => {{ + if (['line', 'name', 'stack', 'column', 'message', 'sourceURL', 'originalLine', 'originalColumn'].includes(key)) {{ + return; + }} + extra[key] = e[key]; + }}); + if (Object.keys(extra).length > 0) {{ + err["extra"] = extra; + }} + return {STRINGIFY_ERROR_JS}; +}} + const scripts = new Map(); {functions} {registrations} @@ -287,7 +303,7 @@ for await (const line of Readline.createInterface({{ input: process.stdin }})) { const res = await entry.module.main(...mainArgs); console.log("wm_res[success]:" + JSON.stringify(res ?? null, (key, value) => typeof value === 'undefined' ? null : value)); }} catch (e) {{ - console.log("wm_res[error]:" + JSON.stringify({{ message: e.message, name: e.name, stack: e.stack, line: argsJson }})); + console.log("wm_res[error]:" + errorJson(e)); }} continue; }} @@ -301,7 +317,7 @@ for await (const line of Readline.createInterface({{ input: process.stdin }})) { const res = await entry.module.main(...args); console.log("wm_res[success]:" + JSON.stringify(res ?? null, (key, value) => typeof value === 'undefined' ? null : value)); }} catch (e) {{ - console.log("wm_res[error]:" + JSON.stringify({{ message: e.message, name: e.name, stack: e.stack, line: argsJson }})); + console.log("wm_res[error]:" + errorJson(e)); }} continue; }} @@ -335,7 +351,7 @@ for await (const line of Readline.createInterface({{ input: process.stdin }})) { const res = await entry.module.main(...mainArgs); console.log("wm_res[success]:" + JSON.stringify(res ?? null, (key, value) => typeof value === 'undefined' ? null : value)); }} catch (e) {{ - console.log("wm_res[error]:" + JSON.stringify({{ message: e.message, name: e.name, stack: e.stack, line: argsJson }})); + console.log("wm_res[error]:" + errorJson(e)); }} continue; }} @@ -361,7 +377,7 @@ for await (const line of Readline.createInterface({{ input: process.stdin }})) { const res = await entry.module.main(...args); console.log("wm_res[success]:" + JSON.stringify(res ?? null, (key, value) => typeof value === 'undefined' ? null : value)); }} catch (e) {{ - console.log("wm_res[error]:" + JSON.stringify({{ message: e.message, name: e.name, stack: e.stack, line: argsJson }})); + console.log("wm_res[error]:" + errorJson(e)); }} continue; }} @@ -746,7 +762,7 @@ registry = {} .map(|x| format!("[install.scopes]\n{x}")) .unwrap_or("".to_string()) ); - tracing::debug!("Writing following bunfig.toml: {bunfig_toml}"); + tracing::debug!("Writing bunfig.toml ({} bytes)", bunfig_toml.len()); let _ = write_file(&job_dir, BUN_CONFIG_FILE, &bunfig_toml)?; } Ok(()) @@ -3516,7 +3532,7 @@ pub async fn handle_wac_v2_output( }; use serde_json::Value; use windmill_common::get_latest_flow_version_info_for_path; - use windmill_common::jobs::{script_path_to_payload, JobKind, JobPayload, RawCode}; + use windmill_common::jobs::{script_path_to_payload, JobKind, JobPayload, RawCode, RunOrigin}; use windmill_common::runnable_ref::RunnableRef; use windmill_common::runnable_settings::{ ConcurrencySettings, ConcurrencySettingsWithCustom, DebouncingSettings, @@ -3797,6 +3813,7 @@ pub async fn handle_wac_v2_output( // Resolve script path to job payload (handles hash, lang, etc.) let (payload, _, _, _, _, on_behalf_of) = script_path_to_payload( &script, + RunOrigin::Deployed, None, // no authed db for background workers db.clone(), &job.workspace_id, @@ -4890,6 +4907,25 @@ async fn handle_dedicated_bunnative( (result, success, preprocessed, logs) }; + let result = if success { + result + } else { + let flow_path = crate::common::parent_flow_path(job.parent_job, &db.into()) + .await + .unwrap_or_else(|e| { + tracing::warn!("could not fetch flow path of job {id}: {e:#}"); + None + }); + crate::js_eval::add_step_context( + &result, + job.flow_step_id.as_deref(), + Some(&id.to_string()), + flow_path.as_deref(), + ) + .map(Arc::new) + .unwrap_or(result) + }; + append_logs(&id, &job.workspace_id, logs, &db.into()).await; job_completed_tx.send_job(JobCompleted { job: MiniCompletedJob::from(job), diff --git a/backend/windmill-worker/src/common.rs b/backend/windmill-worker/src/common.rs index 3185e7e01f..132eda4e8c 100644 --- a/backend/windmill-worker/src/common.rs +++ b/backend/windmill-worker/src/common.rs @@ -526,6 +526,23 @@ pub fn capitalize(s: &str) -> String { } } +/// `WM_FLOW_PATH` of a job: the path of the flow it is a step of. +pub async fn parent_flow_path( + parent_job: Option<uuid::Uuid>, + db: &Connection, +) -> Result<Option<String>, Error> { + match (parent_job, db) { + (Some(uuid), Connection::Sql(db)) => Ok(sqlx::query_scalar!( + "SELECT runnable_path FROM v2_job WHERE id = $1", + uuid + ) + .fetch_optional(db) + .await? + .flatten()), + _ => Ok(None), + } +} + #[tracing::instrument(level = "trace", skip_all)] pub async fn get_reserved_variables( job: &MiniPulledJob, @@ -535,18 +552,8 @@ pub async fn get_reserved_variables( ) -> Result<HashMap<String, String>, Error> { let flow_path = if parent_runnable_path.is_some() { parent_runnable_path - } else if let Some(uuid) = job.parent_job { - match db { - Connection::Sql(db) => { - sqlx::query_scalar!("SELECT runnable_path FROM v2_job WHERE id = $1", uuid) - .fetch_optional(db) - .await? - .flatten() - } - Connection::Http(_) => None, - } } else { - None + parent_flow_path(job.parent_job, db).await? }; let tested_runnable = match (&job.trigger_kind, &job.trigger) { @@ -686,6 +693,119 @@ pub struct OccupancyMetrics { pub total_duration_of_running_jobs: f32, pub worker_occupancy_rate_history: Vec<(f32, f32)>, pub start_time: Instant, + /// Set when the worker runs dedicated subprocesses. Its busy time then replaces the main + /// loop's timers, which never see the jobs the loop only hands over. + pub dedicated: Option<Arc<DedicatedWorkerState>>, +} + +/// Shared by a worker's main loop and its dedicated subprocesses, which find it by worker name. +#[derive(Default)] +pub struct DedicatedWorkerState { + busy: std::sync::Mutex<Busy>, + /// Jobs handed to a dedicated subprocess and not yet done with. Nothing else pings them + /// while they wait in its channel or run in it, or they are restarted as zombies and run + /// twice. + in_flight: std::sync::Mutex<HashSet<uuid::Uuid>>, +} + +#[derive(Default)] +struct Busy { + running: usize, + since: Option<Instant>, + total_secs: f32, +} + +lazy_static! { + static ref DEDICATED_WORKER_STATES: std::sync::Mutex<HashMap<String, std::sync::Weak<DedicatedWorkerState>>> = + std::sync::Mutex::new(HashMap::new()); +} + +impl DedicatedWorkerState { + /// Keyed by worker name, which keeps the native mode's several workers per process apart. + pub fn for_worker(worker_name: &str) -> Arc<Self> { + let mut states = DEDICATED_WORKER_STATES + .lock() + .unwrap_or_else(|e| e.into_inner()); + if let Some(state) = states.get(worker_name).and_then(|s| s.upgrade()) { + return state; + } + let state = Arc::new(Self::default()); + states.insert(worker_name.to_string(), Arc::downgrade(&state)); + state + } + + /// Taken by a dedicated subprocess on receiving a job. Dropping it ends the job's in-flight + /// pings, so a job dropped unfinished is left to the zombie recovery. + pub fn received(self: &Arc<Self>, job_id: uuid::Uuid) -> HandedOver { + HandedOver { state: self.clone(), job_id } + } + + /// Counts the worker as busy until the guard drops, overlapping jobs once. + pub fn start_busy(self: &Arc<Self>, job: Option<HandedOver>) -> BusyGuard { + let mut s = self.busy.lock().unwrap_or_else(|e| e.into_inner()); + if s.running == 0 { + s.since = Some(Instant::now()); + } + s.running += 1; + BusyGuard { state: self.clone(), _job: job } + } + + fn busy_secs(&self) -> f32 { + let s = self.busy.lock().unwrap_or_else(|e| e.into_inner()); + s.total_secs + s.since.map(|x| x.elapsed().as_secs_f32()).unwrap_or(0.0) + } + + pub fn hand_over(&self, job_id: uuid::Uuid) { + self.in_flight_set().insert(job_id); + } + + pub fn take_back(&self, job_id: &uuid::Uuid) { + self.in_flight_set().remove(job_id); + } + + pub(crate) fn in_flight(&self) -> Vec<uuid::Uuid> { + self.in_flight_set().iter().copied().collect() + } + + /// Drops the jobs of `pinged` that `still_running` lacks; those handed over meanwhile stay. + pub(crate) fn prune_in_flight(&self, pinged: &[uuid::Uuid], still_running: &[uuid::Uuid]) { + let pinged: HashSet<_> = pinged.iter().collect(); + let still_running: HashSet<_> = still_running.iter().collect(); + self.in_flight_set() + .retain(|id| still_running.contains(id) || !pinged.contains(id)); + } + + fn in_flight_set(&self) -> std::sync::MutexGuard<'_, HashSet<uuid::Uuid>> { + self.in_flight.lock().unwrap_or_else(|e| e.into_inner()) + } +} + +pub struct HandedOver { + state: Arc<DedicatedWorkerState>, + job_id: uuid::Uuid, +} + +impl Drop for HandedOver { + fn drop(&mut self) { + self.state.take_back(&self.job_id); + } +} + +pub struct BusyGuard { + state: Arc<DedicatedWorkerState>, + _job: Option<HandedOver>, +} + +impl Drop for BusyGuard { + fn drop(&mut self) { + let mut s = self.state.busy.lock().unwrap_or_else(|e| e.into_inner()); + s.running = s.running.saturating_sub(1); + if s.running == 0 { + if let Some(since) = s.since.take() { + s.total_secs += since.elapsed().as_secs_f32(); + } + } + } } pub struct OccupancyResult { @@ -702,6 +822,7 @@ impl OccupancyMetrics { total_duration_of_running_jobs: 0.0, worker_occupancy_rate_history: Vec::new(), start_time, + dedicated: None, } } @@ -711,7 +832,12 @@ impl OccupancyMetrics { .running_job_started_at .map(|started_at| started_at.elapsed().as_secs_f32()) .unwrap_or(0.0); - let total_occupation = metrics.total_duration_of_running_jobs + current_occupied_duration; + // A worker with dedicated subprocesses also counts the jobs its main loop runs in the + // busy time, so that one overlapping the other is counted once. + let total_occupation = match metrics.dedicated.as_ref() { + Some(dedicated) => dedicated.busy_secs(), + None => metrics.total_duration_of_running_jobs + current_occupied_duration, + }; let elapsed = metrics.start_time.elapsed().as_secs_f32(); @@ -2166,6 +2292,17 @@ pub fn extract_flow_root(runnable_path: &str) -> Option<&str> { .and_then(|c| c.get(1).map(|m| m.as_str())) } +/// Dedicated runner key of a dedicated flow's `type: script` step. Its job runs at the +/// script's own path, so it is found by the flow's dedicated tag and its step id instead, and +/// by the version it runs: a runner never reloads, so after a redeploy it must not serve it. +pub fn flow_script_step_runner_key( + flow_tag: &str, + step_id: &str, + hash: windmill_common::scripts::ScriptHash, +) -> String { + format!("{flow_tag}/{step_id}@{hash}") +} + pub fn build_http_client(timeout_duration: std::time::Duration) -> error::Result<Client> { configure_client( reqwest::ClientBuilder::new() @@ -2604,6 +2741,31 @@ mod tests { use serde_json::json; use windmill_common::client::AuthedClient; + #[test] + fn dedicated_worker_counts_overlapping_jobs_once() { + let step = std::time::Duration::from_millis(50); + let state = Arc::new(DedicatedWorkerState::default()); + let handed_over = uuid::Uuid::new_v4(); + state.hand_over(handed_over); + let started = Instant::now(); + let dedicated = state.start_busy(Some(state.received(handed_over))); + std::thread::sleep(step); + let inline = state.start_busy(None); + std::thread::sleep(step); + drop(dedicated); + assert!(state.in_flight().is_empty()); + std::thread::sleep(step); + drop(inline); + let busy_for = started.elapsed().as_secs_f32(); + let busy = state.busy_secs(); + assert!( + (busy - busy_for).abs() < 0.01, + "busy {busy}s over {busy_for}s" + ); + std::thread::sleep(step); + assert_eq!(state.busy_secs(), busy); + } + fn test_client() -> AuthedClient { AuthedClient::new( "http://localhost:0".to_string(), diff --git a/backend/windmill-worker/src/csharp_executor.rs b/backend/windmill-worker/src/csharp_executor.rs index 87213223e7..293401a508 100644 --- a/backend/windmill-worker/src/csharp_executor.rs +++ b/backend/windmill-worker/src/csharp_executor.rs @@ -72,6 +72,9 @@ lazy_static::lazy_static! { const CSHARP_OBJECT_STORE_PREFIX: &str = const_format::concatcp!(crate::global_cache::TARGET, "_csharpbin/"); +#[cfg(feature = "csharp")] +const CSHARP_WRAPPER_VERSION: &str = "wrapper-v2"; + /// Cache key of a C# build. The run path and the deploy-time prebuild must derive it the /// same way or the prebuilt binary is never found and gets rebuilt on first run. #[cfg(feature = "csharp")] @@ -83,11 +86,14 @@ async fn csharp_cache_key( ) -> String { // The SDK project globs every `.cs` under the job dir, so companion modules are // compiled into the binary this key names and have to be part of it. + // The generated wrapper is compiled into the binary too: bump the version when it + // changes, or binaries built with the previous wrapper keep running. let base = format!( - "{}{}{}", + "{}{}{}{}", code, requirements_o.unwrap_or(""), - DOTNET_TARGET_FRAMEWORK.as_str() + DOTNET_TARGET_FRAMEWORK.as_str(), + CSHARP_WRAPPER_VERSION ); let mut hash = crate::worker::artifact_cache_name(base, modules); hash.push_str(&crate::workspace_registry_cache_suffix(w_id).await); @@ -266,28 +272,74 @@ fn gen_cs_proj( write_file(job_dir, "Script.cs", code.as_str())?; let sig_meta = windmill_parser_csharp::parse_csharp_sig_meta(code.as_str())?; - let sig = sig_meta.main_sig; - let spread = &sig - .args - .clone() - .into_iter() - .map(|x| format!("parsedArgs.{}", &x.name)) - .join(", "); - let args_class_body = &sig - .args - .into_iter() + let args = &sig_meta.main_sig.args; + let class_name = sig_meta.class_name.unwrap_or("Script".to_string()); + let otyp = |x: &windmill_parser::Arg| { + x.otyp + .clone() + .ok_or(anyhow!("Type not found for argument {}", x.name)) + }; + let args_class_body = &args + .iter() .map(|x| { + // The schema keys a verbatim identifier (`@class`) with its `@`, which is not + // part of the C# name the serializer would match on. + let json_name = if x.name.starts_with('@') { + format!( + "[System.Text.Json.Serialization.JsonPropertyName(\"{}\")] ", + x.name + ) + } else { + String::new() + }; Ok(format!( - " public {} {} {{ get; set; }}", - x.otyp - .ok_or(anyhow!("Type not found for argument {}", x.name))?, - &x.name, + " {json_name}public {} {} {{ get; set; }}", + otyp(x)?, + &x.name )) }) .collect::<Result<Vec<String>, anyhow::Error>>()? .join("\n"); - let class_name = sig_meta.class_name.unwrap_or("Script".to_string()); + // An argument left out of args.json must take the default declared on Main, not + // default(T). It is read back from the compiled method because the default + // expression may name a constant the wrapper cannot see. The parser does not list + // every parameter (`params T[] x` is not one), so Main is matched on the names it + // does list and each default is looked up by name, never by position. + let mut resolve_defaults = String::new(); + if args.iter().any(|x| x.has_default) { + let names = args + .iter() + .map(|x| format!("\"{}\"", x.name.trim_start_matches('@'))) + .join(", "); + resolve_defaults.push_str(&format!( + r#" + using JsonDocument __argsDoc = JsonDocument.Parse(__argsJson); + var __mainParams = typeof({class_name}) + .GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static) + .First(m => m.Name == "Main" && new string[] {{ {names} }}.All(n => m.GetParameters().Any(p => p.Name == n))) + .GetParameters();"# + )); + for (i, x) in args.iter().enumerate().filter(|(_, x)| x.has_default) { + resolve_defaults.push_str(&format!( + "\n {t} __arg{i} = __argsDoc.RootElement.TryGetProperty(\"{n}\", out _) ? parsedArgs.{n} : DeclaredDefault<{t}>(__mainParams.First(p => p.Name == \"{c}\"));", + t = otyp(x)?, + n = x.name, + c = x.name.trim_start_matches('@'), + )); + } + } + let spread = &args + .iter() + .enumerate() + .map(|(i, x)| { + if x.has_default { + format!("__arg{i}") + } else { + format!("parsedArgs.{}", &x.name) + } + }) + .join(", "); let script_call = match (sig_meta.is_async, sig_meta.returns_void) { (true, true) => format!( @@ -327,6 +379,7 @@ fn gen_cs_proj( &format!( r#"using System; using System.IO; +using System.Linq; using System.Text.Json; using System.Threading.Tasks; @@ -338,13 +391,15 @@ namespace WindmillScriptCSharpInternal {{ class Wrapper {{ + static T DeclaredDefault<T>(System.Reflection.ParameterInfo p) => p.DefaultValue is T v ? v : default; + static void Main(string[] args) {{ - using FileStream fs = File.OpenRead("args.json"); - Args parsedArgs = JsonSerializer.Deserialize<Args>(fs); + string __argsJson = File.ReadAllText("args.json"); + Args parsedArgs = JsonSerializer.Deserialize<Args>(__argsJson); try - {{ + {{{resolve_defaults} {script_call} }} catch (Exception ex) diff --git a/backend/windmill-worker/src/deno_executor.rs b/backend/windmill-worker/src/deno_executor.rs index e9b27e2a9a..94ba805b87 100644 --- a/backend/windmill-worker/src/deno_executor.rs +++ b/backend/windmill-worker/src/deno_executor.rs @@ -749,7 +749,7 @@ pub fn generate_dedicated_worker_wrapper(inner_content: &str) -> Result<String> let res: any = await main(...[ {spread} ]); console.log("wm_res[success]:" + JSON.stringify(res ?? null, (key, value) => typeof value === 'undefined' ? null : value) + '\n'); }} catch (e) {{ - console.log("wm_res[error]:" + JSON.stringify({{ message: e.message, name: e.name, stack: e.stack, line: line }}) + '\n'); + console.log("wm_res[error]:" + JSON.stringify({{ message: e.message, name: e.name, stack: e.stack }}) + '\n'); }} continue; }}"# @@ -792,7 +792,7 @@ for await (const chunk of Deno.stdin.readable) {{ let res: any = await main(...[ {spread} ]); console.log("wm_res[success]:" + JSON.stringify(res ?? null, (key, value) => typeof value === 'undefined' ? null : value) + '\n'); }} catch (e) {{ - console.log("wm_res[error]:" + JSON.stringify({{ message: e.message, name: e.name, stack: e.stack, line: argsJson }}) + '\n'); + console.log("wm_res[error]:" + JSON.stringify({{ message: e.message, name: e.name, stack: e.stack }}) + '\n'); }} continue; }} diff --git a/backend/windmill-worker/src/handle_child.rs b/backend/windmill-worker/src/handle_child.rs index 31eb8034f9..3a1b835707 100644 --- a/backend/windmill-worker/src/handle_child.rs +++ b/backend/windmill-worker/src/handle_child.rs @@ -1,8 +1,8 @@ use futures::Future; #[cfg(any(target_os = "linux", target_os = "macos"))] -use nix::sys::signal::{self, Signal}; -#[cfg(any(target_os = "linux", target_os = "macos"))] +use nix::sys::signal::Signal; +#[cfg(target_os = "linux")] use nix::unistd::Pid; use process_wrap::tokio::TokioChildWrapper; use windmill_common::agent_workers::PingJobStatusResponse; @@ -11,7 +11,6 @@ use windmill_common::result_stream::extract_stream_from_logs; #[cfg(windows)] use std::process::Stdio; -use tokio::fs::File; #[cfg(windows)] use tokio::process::Command; use windmill_common::error::to_anyhow; @@ -153,6 +152,17 @@ struct OutputLine { line: String, } +#[cfg(any(target_os = "linux", target_os = "macos"))] +fn send_job_signal(child: &dyn TokioChildWrapper, sig: Signal) { + // Under the ProcessGroup wrap this is a killpg on the group recorded at spawn, so a + // wrapper that does not forward signals (unshare --fork, sh) cannot shield the job. + // It stops at a wrapper that starts its own group (tini, nsjail without + // skip_setsid), which must forward it. Without the wrap it signals the child only. + if let Err(e) = child.signal(sig as i32) { + tracing::debug!("failed to send {sig} to the job process: {e}"); + } +} + /// - wait until child exits and return with exit status /// - read lines from stdout and stderr and append them to the "queue"."logs" /// quitting early if output exceedes MAX_LOG_SIZE characters (not bytes) @@ -381,11 +391,10 @@ pub async fn handle_child( if cfg!(any(target_os = "linux", target_os = "macos")) { s } else { "none" } }; let kill = async { - #[allow(unused_variables)] - if let Some(id) = child.id() { + if child.id().is_some() { if *MAX_WAIT_FOR_SIGINT > 0 { #[cfg(any(target_os = "linux", target_os = "macos"))] - signal::kill(Pid::from_raw(id as i32), Signal::SIGINT).unwrap(); + send_job_signal(child.as_ref(), Signal::SIGINT); for _ in 0..*MAX_WAIT_FOR_SIGINT { if child.try_wait().is_ok_and(|x| x.is_some()) { @@ -400,7 +409,7 @@ pub async fn handle_child( } if sigterm { #[cfg(any(target_os = "linux", target_os = "macos"))] - signal::kill(Pid::from_raw(id as i32), Signal::SIGTERM).unwrap(); + send_job_signal(child.as_ref(), Signal::SIGTERM); for _ in 0..*MAX_WAIT_FOR_SIGTERM { if child.try_wait().is_ok_and(|x| x.is_some()) { @@ -797,55 +806,88 @@ async fn handle_wac_step_marker( Ok(()) } -pub(crate) async fn get_mem_peak(pid: Option<u32>, nsjail: bool) -> i32 { - if pid.is_none() { - return -1; - } - let pid = if nsjail { - // Read /proc/<nsjail_pid>/task/<nsjail_pid>/children and extract pid - let nsjail_pid = pid.unwrap(); - let children_path = format!("/proc/{}/task/{}/children", nsjail_pid, nsjail_pid); - if let Ok(mut file) = File::open(children_path).await { - let mut contents = String::new(); - if tokio::io::AsyncReadExt::read_to_string(&mut file, &mut contents) - .await - .is_ok() - { - if let Some(child_pid) = contents.split_whitespace().next() { - if let Ok(child_pid) = child_pid.parse::<u32>() { - child_pid - } else { - return -1; - } - } else { - return -1; - } - } else { - return -1; - } - } else { - return -1; - } - } else { - pid.unwrap() +lazy_static::lazy_static! { + /// Process names of the wrappers a job may run under, whose own memory is not the job's: + /// nsjail when a script annotation jails the job while `nsjail` is not passed (global + /// sandboxing off), and `unshare` (then optionally `tini`) under pid namespace isolation. + /// The configured binaries are included as the kernel names them: basename, 15 bytes. + static ref MEM_PEAK_WRAPPERS: Vec<String> = { + let comm = |path: &str| { + let name = std::path::Path::new(path) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + String::from_utf8_lossy(&name.as_bytes()[..name.len().min(15)]).into_owned() + }; + let mut names: Vec<String> = + ["nsjail", "unshare", "tini", "tini-static"].map(String::from).to_vec(); + names.push(comm(crate::NSJAIL_PATH.as_str())); + names.push(comm(crate::UNSHARE_TINI_PATH.as_str())); + names }; +} - if let Ok(file) = File::open(format!("/proc/{}/status", pid)).await { - let mut lines = BufReader::new(file).lines(); - while let Some(line) = lines.next_line().await.unwrap_or(None) { - if line.starts_with("VmHWM:") { - return line - .split_whitespace() - .nth(1) - .and_then(|s| s.parse::<i32>().ok()) - .unwrap_or(-1); - }; - } - -2 - } else { - // rand::random::<i32>() % 100 // to remove - used to fake memory data on MacOS - -3 +pub(crate) async fn get_mem_peak(pid: Option<u32>, nsjail: bool) -> i32 { + get_mem_peak_in( + std::path::Path::new("/proc"), + pid, + nsjail, + &MEM_PEAK_WRAPPERS, + ) + .await +} + +async fn get_mem_peak_in( + proc_root: &std::path::Path, + pid: Option<u32>, + nsjail: bool, + wrappers: &[String], +) -> i32 { + let Some(mut pid) = pid else { + return -1; + }; + if nsjail { + let Some(child) = first_child_pid(proc_root, pid).await else { + return -1; + }; + pid = child; } + // unshare -> tini -> job + for _ in 0..3 { + let Ok(status) = tokio::fs::read_to_string(proc_root.join(format!("{pid}/status"))).await + else { + return -3; + }; + let name = status + .lines() + .find_map(|l| l.strip_prefix("Name:")) + .map(str::trim); + if name.is_some_and(|n| wrappers.iter().any(|w| w == n)) { + // The wrapper may not have forked the job yet. + let Some(child) = first_child_pid(proc_root, pid).await else { + return -1; + }; + pid = child; + continue; + } + return status + .lines() + .find_map(|l| l.strip_prefix("VmHWM:")) + .and_then(|v| v.split_whitespace().next()) + .and_then(|v| v.parse::<i32>().ok()) + .unwrap_or(-2); + } + -1 +} + +async fn first_child_pid(proc_root: &std::path::Path, pid: u32) -> Option<u32> { + tokio::fs::read_to_string(proc_root.join(format!("{pid}/task/{pid}/children"))) + .await + .ok()? + .split_whitespace() + .next()? + .parse() + .ok() } /// The job state a command run outside the main script needs to stay @@ -1326,4 +1368,85 @@ mod tests { ] ); } + + #[cfg(any(target_os = "linux", target_os = "macos"))] + #[tokio::test] + async fn send_job_signal_reaches_child_behind_a_wrapper_ignoring_sigterm() { + use std::process::Stdio; + let mut cmd = tokio::process::Command::new("sh"); + cmd.args(["-c", "sleep 60 &\ntrap '' TERM\necho ready\nwait"]) + .stdout(Stdio::piped()); + let mut child = crate::common::start_child_process(cmd, "sh", false) + .await + .unwrap(); + + let stdout = child.stdout().take().unwrap(); + let mut lines = BufReader::new(stdout).lines(); + assert_eq!(lines.next_line().await.unwrap().as_deref(), Some("ready")); + + send_job_signal(child.as_ref(), Signal::SIGTERM); + + tokio::time::timeout(Duration::from_secs(2), Box::into_pin(child.wait())) + .await + .expect("wrapper should exit once its child receives SIGTERM") + .unwrap(); + } + + #[tokio::test] + async fn mem_peak_is_read_past_wrapper_processes() { + let dir = tempfile::tempdir().unwrap(); + let proc = dir.path(); + let write_proc = |pid: u32, name: &str, hwm_kb: u32, child: Option<u32>| { + let task_dir = proc.join(format!("{pid}/task/{pid}")); + std::fs::create_dir_all(&task_dir).unwrap(); + std::fs::write( + proc.join(format!("{pid}/status")), + format!("Name:\t{name}\nVmPeak:\t{hwm_kb} kB\nVmHWM:\t {hwm_kb} kB\n"), + ) + .unwrap(); + let children = child.map(|c| format!("{c} ")).unwrap_or_default(); + std::fs::write(task_dir.join("children"), children).unwrap(); + }; + + // unshare -> tini -> python3 + write_proc(100, "unshare", 1692, Some(101)); + write_proc(101, "tini", 820, Some(102)); + write_proc(102, "python3", 115616, None); + // nsjail -> bun + write_proc(200, "nsjail", 11056, Some(201)); + write_proc(201, "bun", 236936, None); + // a wrapper that has not forked its child yet + write_proc(300, "unshare", 1692, None); + // a jail binary under another name, known only from the flag + write_proc(400, "nsjail-3.4", 11056, Some(401)); + write_proc(401, "python3", 115616, None); + + let wrappers: Vec<String> = ["nsjail", "unshare", "tini"].map(String::from).to_vec(); + assert_eq!( + get_mem_peak_in(proc, Some(100), false, &wrappers).await, + 115616 + ); + assert_eq!( + get_mem_peak_in(proc, Some(102), false, &wrappers).await, + 115616 + ); + assert_eq!( + get_mem_peak_in(proc, Some(200), false, &wrappers).await, + 236936 + ); + assert_eq!(get_mem_peak_in(proc, Some(300), false, &wrappers).await, -1); + assert_eq!(get_mem_peak_in(proc, Some(999), false, &wrappers).await, -3); + assert_eq!( + get_mem_peak_in(proc, Some(400), true, &wrappers).await, + 115616 + ); + assert_eq!( + get_mem_peak_in(proc, Some(200), true, &wrappers).await, + 236936 + ); + assert_eq!( + get_mem_peak_in(proc, Some(400), false, &wrappers).await, + 11056 + ); + } } diff --git a/backend/windmill-worker/src/js_eval.rs b/backend/windmill-worker/src/js_eval.rs index 2e78f0aae8..66499e4507 100644 --- a/backend/windmill-worker/src/js_eval.rs +++ b/backend/windmill-worker/src/js_eval.rs @@ -107,6 +107,43 @@ pub async fn eval_timeout( } } +/// [`eval_timeout`] for an expression that only reads `flow_input`, `flow_env` and `results`, +/// bounded by `timeout` in total: no retry, and QuickJS is interrupted at the limit. +pub async fn eval_within( + timeout: std::time::Duration, + expr: &str, + flow_input: mappable_rc::Marc<HashMap<String, Box<RawValue>>>, + flow_env: Option<&HashMap<String, Box<RawValue>>>, + authed_client: &AuthedClient, + by_id: &IdContext, +) -> anyhow::Result<Box<RawValue>> { + let expr = expr.trim(); + if let Some(value) = + windmill_jseval::try_exact_property_access(expr, Some(&flow_input), flow_env) + { + return Ok(value); + } + let eval = async { + if let Some(result) = windmill_jseval::handle_full_regex(expr, authed_client, by_id).await { + return result; + } + windmill_jseval::eval_timeout_quickjs_within( + timeout, + expr.to_string(), + HashMap::new(), + Some(flow_input), + flow_env, + Some(authed_client), + Some(by_id), + None, + ) + .await + }; + tokio::time::timeout(timeout, eval) + .await + .map_err(|_| anyhow::anyhow!("`{expr}` took longer than {}ms", timeout.as_millis()))? +} + /// Adds `step_id`, `job_id` and `flow_path` to a native script's thrown error, as the /// subprocess wrappers do from the same env vars. pub fn with_step_context( @@ -117,19 +154,38 @@ pub fn with_step_context( let Error::ExecutionRawError(raw) = &e else { return e; }; - let Ok(serde_json::Value::Object(mut err)) = serde_json::from_str(raw.get()) else { - return e; + let var = |k: &str| reserved_variables.get(k).map(String::as_str); + match add_step_context( + raw, + var("WM_FLOW_STEP_ID"), + var("WM_JOB_ID"), + var("WM_FLOW_PATH"), + ) { + Some(raw) => Error::ExecutionRawError(raw), + None => e, + } +} + +/// Returns `err` with the non-empty context fields set, or `None` if it is not a JSON object. +pub fn add_step_context( + err: &RawValue, + step_id: Option<&str>, + job_id: Option<&str>, + flow_path: Option<&str>, +) -> Option<Box<RawValue>> { + let Ok(serde_json::Value::Object(mut err)) = serde_json::from_str(err.get()) else { + return None; }; - for (key, var) in [ - ("step_id", "WM_FLOW_STEP_ID"), - ("job_id", "WM_JOB_ID"), - ("flow_path", "WM_FLOW_PATH"), + for (key, v) in [ + ("step_id", step_id), + ("job_id", job_id), + ("flow_path", flow_path), ] { - if let Some(v) = reserved_variables.get(var).filter(|v| !v.is_empty()) { - err.insert(key.to_string(), serde_json::Value::String(v.clone())); + if let Some(v) = v.filter(|v| !v.is_empty()) { + err.insert(key.to_string(), serde_json::Value::String(v.to_string())); } } - Error::ExecutionRawError(windmill_common::worker::to_raw_value(&err)) + Some(windmill_common::worker::to_raw_value(&err)) } #[cfg(feature = "deno_core")] diff --git a/backend/windmill-worker/src/python_executor.rs b/backend/windmill-worker/src/python_executor.rs index 4486620ead..b573a20313 100644 --- a/backend/windmill-worker/src/python_executor.rs +++ b/backend/windmill-worker/src/python_executor.rs @@ -375,7 +375,7 @@ pub async fn uv_pip_compile( if let Some(exclude_newer) = uv_exclude_newer.as_deref() { args.extend(["--exclude-newer", exclude_newer]); } - tracing::debug!("uv args: {:?}", args); + tracing::debug!("uv args: {:?}", redact_index_urls(&args)); #[cfg(windows)] let uv_cmd = "uv"; @@ -1619,6 +1619,27 @@ from datetime import datetime, date scripts = {{}} +# `step_id`, `job_id` and `flow_path` are per job, so the worker adds them, not this process. +def error_json(e, tb): + err = {{ "message": str(e), "name": e.__class__.__name__, "stack": '\n'.join(tb[1:]) }} + extra = getattr(e, '__dict__', None) + if extra: + err['extra'] = extra + try: + return json.dumps(err, separators=(',', ':'), default=str).replace('\n', '') + except Exception: + pass + # A cyclic attribute would raise here and end the process every later job runs in. + safe = {{}} + for k, v in extra.items(): + try: + json.dumps(v, default=str) + safe[k] = v + except Exception: + safe[k] = '[unserializable]' + err['extra'] = safe + return json.dumps(err, separators=(',', ':'), default=str).replace('\n', '') + def to_b_64(v: bytes): b64 = base64.b64encode(v) return b64.decode('ascii') @@ -1677,7 +1698,7 @@ for line in sys.stdin: except BaseException as e: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.format_tb(exc_traceback) - err_json = json.dumps({{ "message": str(e), "name": e.__class__.__name__, "stack": '\n'.join(tb[1:]) }}, separators=(',', ':'), default=str).replace('\n', '') + err_json = error_json(e, tb) sys.stdout.write("wm_res[error]:" + err_json + "\n") sys.stdout.flush() continue @@ -1705,7 +1726,7 @@ for line in sys.stdin: except BaseException as e: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.format_tb(exc_traceback) - err_json = json.dumps({{ "message": str(e), "name": e.__class__.__name__, "stack": '\n'.join(tb[1:]) }}, separators=(',', ':'), default=str).replace('\n', '') + err_json = error_json(e, tb) sys.stdout.write("wm_res[error]:" + err_json + "\n") sys.stdout.flush() continue @@ -1723,7 +1744,7 @@ for line in sys.stdin: except BaseException as e: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.format_tb(exc_traceback) - err_json = json.dumps({{ "message": str(e), "name": e.__class__.__name__, "stack": '\n'.join(tb[1:]) }}, separators=(',', ':'), default=str).replace('\n', '') + err_json = error_json(e, tb) sys.stdout.write("wm_res[error]:" + err_json + "\n") sys.stdout.flush() continue @@ -1751,7 +1772,7 @@ for line in sys.stdin: except BaseException as e: exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.format_tb(exc_traceback) - err_json = json.dumps({{ "message": str(e), "name": e.__class__.__name__, "stack": '\n'.join(tb[1:]) }}, separators=(',', ':'), default=str).replace('\n', '') + err_json = error_json(e, tb) sys.stdout.write("wm_res[error]:" + err_json + "\n") sys.stdout.flush() continue @@ -2488,7 +2509,10 @@ async fn spawn_uv_install( envs.push(("SSL_CERT_FILE", cert_path)); } - tracing::debug!("uv pip install command: {:?}", command_args); + tracing::debug!( + "uv pip install command: {:?}", + redact_index_urls(&command_args) + ); #[cfg(unix)] { @@ -4173,3 +4197,15 @@ mod tests { let _ = std::fs::remove_file(&lock_path); } } + +/// Index URLs routinely embed `user:token@`, so the value after an index flag is not logged. +fn redact_index_urls<'a>(args: &[&'a str]) -> Vec<&'a str> { + let mut redact_next = false; + args.iter() + .map(|a| { + let out = if redact_next { "<redacted>" } else { a }; + redact_next = matches!(*a, "--index-url" | "--extra-index-url"); + out + }) + .collect() +} diff --git a/backend/windmill-worker/src/worker.rs b/backend/windmill-worker/src/worker.rs index ba84819ccb..c482caac60 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -820,6 +820,43 @@ pub fn sleep_queue() -> u64 { } } +/// Pings the jobs the worker handed to its dedicated subprocesses every `NUM_SECS_PING`, until +/// the worker drops `state`. Runs apart from the main loop, which can spend longer than the +/// zombie timeout on a job it runs itself. +fn spawn_dedicated_in_flight_pinger( + db: DB, + worker_name: String, + state: &Arc<crate::common::DedicatedWorkerState>, +) { + let state = Arc::downgrade(state); + tokio::spawn(async move { + loop { + tokio::time::sleep(Duration::from_secs(NUM_SECS_PING)).await; + let Some(state) = state.upgrade() else { + return; + }; + let sent = state.in_flight(); + if sent.is_empty() { + continue; + } + match sqlx::query_scalar::<_, Uuid>( + "UPDATE v2_job_runtime r SET ping = now() + FROM v2_job_queue q + WHERE r.id = ANY($1) AND q.id = r.id AND q.running AND q.worker = $2 + RETURNING r.id", + ) + .bind(&sent[..]) + .bind(&worker_name) + .fetch_all(&db) + .await + { + Ok(still_running) => state.prune_in_flight(&sent, &still_running), + Err(e) => tracing::warn!("failed to ping the jobs of the dedicated workers: {e:#}"), + } + } + }); +} + pub type WorkspaceRegistryMap = std::collections::HashMap<String, std::collections::HashMap<String, serde_json::Value>>; @@ -3462,6 +3499,17 @@ pub async fn run_worker( WORKER_CONFIG.load() ); } + if WORKER_CONFIG.load().fairness_reserve { + tracing::info!( + worker = %worker_name, hostname = %hostname, + "fairness reserve worker: pulls only while a workspace is overloaded, and only other workspaces' jobs" + ); + if !windmill_common::worker::WORKSPACE_FAIRNESS_ENABLED + .load(std::sync::atomic::Ordering::Relaxed) + { + tracing::warn!("fairness reserve worker stays idle: workspace fairness is off"); + } + } // Dedicated workers wait for the init script before installing their dependencies, so it has to // be queued before they are spawned. @@ -3514,6 +3562,13 @@ pub async fn run_worker( Vec<JoinHandle<()>>, ) = (HashMap::new(), vec![]); + let dedicated_state = (!dedicated_workers.is_empty()) + .then(|| crate::common::DedicatedWorkerState::for_worker(&worker_name)); + if let (Some(state), Some(db)) = (dedicated_state.as_ref(), conn.as_sql()) { + spawn_dedicated_in_flight_pinger(db.clone(), worker_name.clone(), state); + } + occupancy_metrics.dedicated = dedicated_state.clone(); + #[cfg(feature = "prometheus")] let _worker_dedicated_channel_queue_send_duration = { if is_dedicated_worker @@ -3833,6 +3888,12 @@ pub async fn run_worker( // Checked after the same-worker channel: a flow this worker already runs // still needs it for its remaining same-worker steps. Ok(None) + } else if dedicated_workers.values().any(|tx| tx.capacity() == 0) { + // Handing a job to a full channel would park this loop until a slot frees, a job + // duration away: the worker would stop pinging, read as gone to the autoscaler, and + // hold the job out of the queue counts it scales on. Leave it queued instead. + tokio::time::sleep(Duration::from_millis(sleep_queue())).await; + continue; } else { match &conn { Connection::Sql(db) => { @@ -3997,6 +4058,7 @@ pub async fn run_worker( otel_set_worker_busy(&worker_name, 1); occupancy_metrics.running_job_started_at = Some(Instant::now()); + let _busy = dedicated_state.as_ref().map(|s| s.start_busy(None)); last_executed_job = None; jobs_executed += 1; @@ -4027,29 +4089,49 @@ pub async fn run_worker( let restricted = job.job_token_scopes.is_some(); if !dedicated_workers.is_empty() && !fails_before_running && !restricted { - let dedicated_worker_tx = job.runnable_path.as_ref().and_then(|path| { - // For flow steps inside branches/loops, runnable_path includes - // nesting segments (e.g. f/flow/branchone-0/a) but the dedicated - // worker map is keyed by flow_root/step_id (e.g. f/flow/a). - // When nesting segments are present, use flow_root + flow_step_id - // to construct the correct key. - let key = - if let Some(flow_root) = crate::common::extract_flow_root(path) { + let dedicated_worker_tx = job + .runnable_path + .as_ref() + .and_then(|path| { + // For flow steps inside branches/loops, runnable_path includes + // nesting segments (e.g. f/flow/branchone-0/a) but the dedicated + // worker map is keyed by flow_root/step_id (e.g. f/flow/a). + // When nesting segments are present, use flow_root + flow_step_id + // to construct the correct key. + let key = if let Some(flow_root) = + crate::common::extract_flow_root(path) + { let step_id = job.flow_step_id.as_deref().unwrap_or(""); format!("{}:{}/{}", job.workspace_id, flow_root, step_id) } else { format!("{}:{}", job.workspace_id, path) }; - dedicated_workers.get(&key) - }); + dedicated_workers.get(&key) + }) + .or_else(|| { + dedicated_workers.get(&crate::common::flow_script_step_runner_key( + &job.tag, + job.flow_step_id.as_deref()?, + job.runnable_id?, + )) + }); if let Some(dedicated_worker_tx) = dedicated_worker_tx { + let job_id = job.id; let dedicated_job = DedicatedWorkerJob { job: Arc::new(job.job()), flow_runners: None, done_tx: None, }; + // Before the send: the subprocess can finish the job and take it + // back before the send returns. + if let Some(state) = dedicated_state.as_ref() { + state.hand_over(job_id); + } if let Err(e) = dedicated_worker_tx.send(dedicated_job).await { tracing::info!("failed to send jobs to dedicated workers. Likely dedicated worker has been shut down. This is normal: {e:?}"); + if let Some(state) = dedicated_state.as_ref() { + state.take_back(&job_id); + } } #[cfg(feature = "benchmark")] @@ -5020,6 +5102,17 @@ pub async fn handle_queued_job( let _masks = RunningJobMasks::register(job.id, &client.token); if job.canceled_by.is_some() { + // An AI agent cancelled while parked ends here, never reaching the handler that marks its + // background calls still running as failed. + if job.kind == JobKind::AIAgent { + if let (Some(parent_job), Some(db)) = (job.parent_job.as_ref(), conn.as_sql()) { + if let Err(e) = + crate::ai::utils::fail_unfinished_action_successes(&db, parent_job).await + { + tracing::error!("Failed to close the background calls of {}: {e}", job.id); + } + } + } return Err(Error::JsonErr(canceled_job_to_result(&job))); } if let Some(e) = &job.pre_run_error { @@ -6972,7 +7065,10 @@ mount {{ if !volume_mounts.is_empty() { let vol_summary: Vec<String> = volume_mounts .iter() - .map(|v| format!("'{}' -> {}", v.name, v.target)) + .map(|v| { + let mode = if v.read_only { " (read-only)" } else { "" }; + format!("'{}' -> {}{mode}", v.name, v.target) + }) .collect(); append_logs( &job.id, diff --git a/backend/windmill-worker/src/worker_flow.rs b/backend/windmill-worker/src/worker_flow.rs index ba587e355e..a65bd58cd6 100644 --- a/backend/windmill-worker/src/worker_flow.rs +++ b/backend/windmill-worker/src/worker_flow.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use std::time::Duration; use crate::common::{cached_result_path, get_root_job_id, save_in_cache, transform_json}; -use crate::js_eval::{eval_timeout, IdContext}; +use crate::js_eval::{eval_timeout, eval_within, IdContext}; use crate::worker_utils::get_tag_and_concurrency; use crate::{ JobCompletedSender, PreviousResult, SameWorkerSender, SendResultPayload, StepFailureKind, @@ -39,12 +39,12 @@ use windmill_common::client::AuthedClient; use windmill_common::db::Authed; use windmill_common::flow_conversations::{add_message_to_conversation_tx, MessageType}; use windmill_common::flow_status::{ - ApprovalConditions, FlowJobDuration, FlowJobsDuration, FlowStatusModuleWParent, + ApprovalConditions, ContinuedOnError, MAX_CONTINUED_ON_ERROR, FlowJobDuration, FlowJobsDuration, FlowStatusModuleWParent, Iterator as FlowIterator, JobResult, }; use windmill_common::flows::{add_virtual_items_if_necessary, Branch, FlowNodeId, StopAfterIf}; use windmill_common::jobs::{ - script_path_to_payload, JobKind, JobPayload, OnBehalfOf, RawCode, TriggerKindLabel, + script_path_to_payload, JobKind, JobPayload, OnBehalfOf, RawCode, RunOrigin, TriggerKindLabel, ENTRYPOINT_OVERRIDE, }; use windmill_common::runnable_ref::RunnableRef; @@ -844,6 +844,7 @@ pub async fn update_flow_status_after_job_completion_internal( add_time!(bench, "process module status START"); let mut nresult = None; + let mut continued_on_error = None; let (inc_step_counter, new_status) = match module_status { FlowStatusModule::InProgress { iterator, @@ -1123,6 +1124,7 @@ pub async fn update_flow_status_after_job_completion_internal( job: job_id_for_status.clone(), flow_jobs: Some(jobs.clone()), flow_jobs_success: flow_jobs_success.clone(), + flow_jobs_labels: module_status.flow_jobs_labels(), flow_jobs_duration: flow_jobs_duration.clone(), branch_chosen: None, approvers: vec![], @@ -1138,6 +1140,7 @@ pub async fn update_flow_status_after_job_completion_internal( job: job_id_for_status.clone(), flow_jobs: Some(jobs.clone()), flow_jobs_success: flow_jobs_success.clone(), + flow_jobs_labels: module_status.flow_jobs_labels(), flow_jobs_duration: flow_jobs_duration.clone(), branch_chosen: None, failed_retries: vec![], @@ -1376,6 +1379,7 @@ pub async fn update_flow_status_after_job_completion_internal( job: job_id_for_status.clone(), flow_jobs, flow_jobs_success, + flow_jobs_labels: module_status.flow_jobs_labels(), flow_jobs_duration, branch_chosen, approvers: vec![], @@ -1412,6 +1416,12 @@ pub async fn update_flow_status_after_job_completion_internal( } else { false }; + if inc { + continued_on_error = Some(ContinuedOnError { + id: module_status.id(), + job: *job_id_for_status, + }); + } if (stop_early && stop_early_err_msg.is_some()) || loop_exhausted_err.is_some() { // if stop_early with error message, we need to set explictely success to false as this function was called with success = true as the job succeeded @@ -1424,6 +1434,7 @@ pub async fn update_flow_status_after_job_completion_internal( job: job_id_for_status.clone(), flow_jobs, flow_jobs_success, + flow_jobs_labels: module_status.flow_jobs_labels(), flow_jobs_duration, branch_chosen, failed_retries: old_status.retry.failed_jobs.clone(), @@ -1610,6 +1621,12 @@ pub async fn update_flow_status_after_job_completion_internal( .map_err(|e| Error::internal_err(format!("error while setting leaf jobs: {e:#}")))?; } + // Written after the flow's own row, keeping the child-to-ancestor lock order of + // every flow completion. + if let (Some(entry), Some(flow_job)) = (continued_on_error, flow_job.as_ref()) { + record_continued_on_error(&mut tx, get_root_job_id(flow_job), entry).await?; + } + flow_job }; @@ -2494,6 +2511,38 @@ async fn set_success_and_duration_in_flow_job_success<'c>( Ok(()) } +/// Records on the root flow a step that failed and that its flow went past because of +/// `continue_on_error`, so that the failure shows on the root run without expanding the +/// subflow it happened in. +async fn record_continued_on_error( + tx: &mut Transaction<'_, Postgres>, + root: Uuid, + entry: ContinuedOnError, +) -> error::Result<()> { + sqlx::query!( + "UPDATE v2_job_status + SET flow_status = JSONB_SET( + flow_status, + ARRAY['continued_on_error'], + COALESCE(flow_status->'continued_on_error', '[]'::jsonb) || JSONB_BUILD_ARRAY($2::jsonb) + ) + WHERE id = $1 + AND flow_status IS NOT NULL + AND JSONB_ARRAY_LENGTH(COALESCE(flow_status->'continued_on_error', '[]'::jsonb)) < $3", + root, + json!(entry), + MAX_CONTINUED_ON_ERROR, + ) + .execute(&mut **tx) + .await + .map_err(|e| { + Error::internal_err(format!( + "error while recording continued_on_error on root flow {root}: {e:#}" + )) + })?; + Ok(()) +} + /// Applies a step's edits to the flow's `v2_job_status` row and reads the flow back, in one /// statement: every UPDATE of that row writes a new row version carrying the whole /// `flow_status`, so the edits must not be split. `leaf_job` is only written here when the flow @@ -3918,6 +3967,7 @@ async fn push_next_flow_job( job: Uuid::nil(), flow_jobs: None, flow_jobs_success: None, + flow_jobs_labels: None, flow_jobs_duration: None, branch_chosen: None, failed_retries: vec![], @@ -4249,24 +4299,26 @@ async fn push_next_flow_job( }; resume_messages.push(to_raw_value(&js)); - audit_log( - &mut *tx, - &audit_author, - "jobs.suspend_resume", - ActionKind::Update, - &flow_job.workspace_id, - flow_job.runnable_path.as_deref(), - Some(HashMap::from([ - ("approved", "false"), - ("job_id", flow_job.id.to_string().as_str()), - ( - "details", - "Suspend timed out without approval but can continue", - ), - ])), - ) - .warn_after_seconds(3) - .await?; + if is_disapproved.is_none() { + audit_log( + &mut *tx, + &audit_author, + "jobs.suspend_resume", + ActionKind::Update, + &flow_job.workspace_id, + flow_job.runnable_path.as_deref(), + Some(HashMap::from([ + ("approved", "false"), + ("job_id", flow_job.id.to_string().as_str()), + ( + "details", + "Suspend timed out without approval but can continue", + ), + ])), + ) + .warn_after_seconds(3) + .await?; + } } sqlx::query!( @@ -4778,6 +4830,7 @@ async fn push_next_flow_job( } else { Some(vec![]) }, + flow_jobs_labels: None, flow_jobs_duration: if branch_chosen.is_some() { None } else { @@ -4899,6 +4952,43 @@ async fn push_next_flow_job( .warn_after_seconds(3) .await?; + // Evaluated before the push transaction opens, so a slow label never holds it. + let (has_iteration_label, mut iteration_labels) = match (&next_status, args.as_ref()) { + (NextStatus::NextLoopIteration { next, .. }, Ok(flow_args)) => { + match &next.iteration_label { + Some(label) => { + let iters = vec![to_raw_value(&next.new_args)]; + let ctx = get_transform_context(&flow_job, "", &status); + let labels = + eval_iteration_labels(label, iters, flow_args, flow_env, client, &ctx) + .await; + (true, labels) + } + None => (false, vec![]), + } + } + ( + NextStatus::AllFlowJobs { + iteration_label: Some(label), + iterator: Some(FlowIterator { itered: Some(itered), .. }), + .. + }, + Ok(flow_args), + ) => { + let iters = itered + .iter() + .take(len) + .enumerate() + .map(|(i, v)| to_raw_value(&json!({ "index": i as i32, "value": v }))) + .collect(); + let ctx = get_transform_context(&flow_job, "", &status); + let labels = + eval_iteration_labels(label, iters, flow_args, flow_env, client, &ctx).await; + (true, labels) + } + _ => (false, vec![]), + }; + let mut tx = db.begin().warn_after_seconds(3).await?; let nargs = args.as_ref(); for (i, mut payload_tag) in job_payloads.into_iter().enumerate() { @@ -4909,6 +4999,37 @@ async fn push_next_flow_job( if let JobPayload::FlowNode { no_inherited_flow_env, .. } = &mut payload_tag.payload { *no_inherited_flow_env = no_flow_env; } + // In a flow test, a subflow with overridden steps runs as a preview of its overridden + // value, as the test's caller rather than as the subflow's on-behalf-of identity: the + // value can hold the test's own code. Only flows of the test run itself inherit the map, + // never a deployed subflow left as is, which may run as someone else. + let test_subflows = status + .test_subflows + .as_ref() + .filter(|_| !matches!(flow_job.kind, JobKind::Flow)); + let mut child_inherits_test_subflows = false; + if let Some(subflows) = test_subflows { + match &payload_tag.payload { + JobPayload::Flow { path, .. } => { + if let Some(v) = subflows.get(path) { + let value: FlowValue = serde_json::from_value(v.clone()).map_err(|e| { + Error::internal_err(format!("test subflow {path}: {e}")) + })?; + payload_tag.payload = JobPayload::RawFlow { + value, + path: Some(path.clone()), + restarted_from: None, + }; + payload_tag.on_behalf_of = None; + child_inherits_test_subflows = true; + } + } + JobPayload::RawFlow { .. } | JobPayload::FlowNode { .. } => { + child_inherits_test_subflows = true; + } + _ => {} + } + } if i % 100 == 0 && i != 0 { tracing::info!(id = %flow_job.id, root_id = %job_root, "pushed (non-commited yet) first {i} subflows of {len}"); // Ping on the pool, outside `tx`, so the zombie flow monitor sees it before the @@ -4961,10 +5082,10 @@ async fn push_next_flow_job( insert_iter_arg(&mut args, "iter".to_string(), to_raw_value(new_args)); args.insert("iter".to_string(), to_raw_value(new_args)); + let args = Marc::new(args); if let Some(input_transforms) = simple_input_transforms { //previous id is none because we do not want to use previous id if we are in a for loop let ctx = get_transform_context(&flow_job, "", &status); - let args = Marc::new(args); step_flow_input = args.clone(); let ti = transform_input( args, @@ -4997,7 +5118,7 @@ async fn push_next_flow_job( Err(&me) } } else { - marc = Marc::new(args); + marc = args; Ok(&marc) } } @@ -5005,6 +5126,7 @@ async fn push_next_flow_job( branchall: None, iterator: Some(FlowIterator { itered, .. }), simple_input_transforms, + .. } => { if let Ok(args) = args.as_ref() { let Some(itered) = itered else { @@ -5022,10 +5144,11 @@ async fn push_next_flow_job( "iter".to_string(), to_raw_value(&json!({ "index": i as i32, "value": itered[i]})), ); + let hm = Marc::new(hm); if let Some(input_transforms) = simple_input_transforms { let ctx = get_transform_context(&flow_job, &previous_id, &status); let ti = transform_input( - Marc::new(hm), + hm, flow_env, env_refs, false, @@ -5054,7 +5177,7 @@ async fn push_next_flow_job( Err(&me) } } else { - marc = Marc::new(hm); + marc = hm; Ok(&marc) } } else { @@ -5299,6 +5422,18 @@ async fn push_next_flow_job( .warn_after_seconds(2) .await?; + if let Some(subflows) = test_subflows.filter(|_| child_inherits_test_subflows) { + sqlx::query!( + "UPDATE v2_job_status SET flow_status = jsonb_set(flow_status, '{test_subflows}', $2) + WHERE id = $1", + uuid, + Json(subflows) as Json<&HashMap<String, serde_json::Value>> + ) + .execute(&mut *inner_tx) + .warn_after_seconds(3) + .await?; + } + if continue_on_same_worker || continue_with_runners { let _ = sqlx::query!( "UPDATE v2_job_queue SET worker = $2 WHERE id = $1", @@ -5499,12 +5634,22 @@ async fn push_next_flow_job( while_loop, mut flow_jobs_success, mut flow_jobs_duration, + flow_jobs_labels, .. }, .. } => { let uuid = one_uuid?; + let flow_jobs_labels = if has_iteration_label { + let mut labels = flow_jobs_labels.unwrap_or_default(); + labels.resize(flow_jobs.len(), None); + labels.push(iteration_labels.pop().flatten()); + Some(labels) + } else { + flow_jobs_labels + }; + flow_jobs.push(uuid); if let Some(flow_jobs_success) = &mut flow_jobs_success { @@ -5528,6 +5673,7 @@ async fn push_next_flow_job( flow_jobs: Some(flow_jobs), flow_jobs_success, flow_jobs_duration, + flow_jobs_labels, branch_chosen: None, branchall: None, id: status_module.id(), @@ -5552,6 +5698,7 @@ async fn push_next_flow_job( flow_jobs_success: Some(vec![None; uuids.len()]), flow_jobs: Some(uuids.clone()), flow_jobs_duration: Some(FlowJobsDuration::new(uuids.len())), + flow_jobs_labels: has_iteration_label.then_some(iteration_labels), branch_chosen: None, branchall, id: status_module.id(), @@ -5582,6 +5729,7 @@ async fn push_next_flow_job( iterator: None, flow_jobs: Some(flow_jobs), flow_jobs_success, + flow_jobs_labels: None, flow_jobs_duration, branch_chosen: None, branchall: Some(status), @@ -5599,6 +5747,7 @@ async fn push_next_flow_job( iterator: None, flow_jobs: None, flow_jobs_success: None, + flow_jobs_labels: None, flow_jobs_duration: None, branch_chosen: Some(branch), branchall: None, @@ -5812,6 +5961,8 @@ struct ForloopNextIteration { flow_jobs: Vec<Uuid>, flow_jobs_success: Option<Vec<Option<bool>>>, flow_jobs_duration: Option<FlowJobsDuration>, + flow_jobs_labels: Option<Vec<Option<String>>>, + iteration_label: Option<InputTransform>, new_args: Iter, while_loop: bool, } @@ -5844,6 +5995,7 @@ enum NextStatus { branchall: Option<BranchAllStatus>, iterator: Option<FlowIterator>, simple_input_transforms: Option<HashMap<String, InputTransform>>, + iteration_label: Option<InputTransform>, }, } @@ -6171,6 +6323,8 @@ async fn compute_next_flow_transform( flow_jobs: flow_jobs, flow_jobs_success: flow_jobs_success, flow_jobs_duration: flow_jobs_duration, + flow_jobs_labels: None, + iteration_label: None, new_args: Iter { index: next_loop_idx as i32, value: windmill_common::worker::to_raw_value(&next_loop_idx), @@ -6190,7 +6344,13 @@ async fn compute_next_flow_transform( } /* forloop modules are expected set `iter: { value: Value, index: usize }` as job arguments */ FlowModuleValue::ForloopFlow { - modules, modules_node, iterator, parallel, squash, .. + modules, + modules_node, + iterator, + parallel, + squash, + iteration_label, + .. } => { // if it's a simple single step flow, we will collapse it as an optimization and need to pass flow_input as an arg let is_simple = !matches!(flow_job.kind, JobKind::FlowPreview) @@ -6230,7 +6390,8 @@ async fn compute_next_flow_transform( ForLoopStatus::EmptyIterator => { Ok(NextFlowTransform::EmptyInnerFlows { branch_chosen: None }) } - ForLoopStatus::NextIteration(ns) => { + ForLoopStatus::NextIteration(mut ns) => { + ns.iteration_label = iteration_label; let start_runners = ns.index == 0 && squash.unwrap_or(false); next_loop_iteration( flow, @@ -6296,6 +6457,7 @@ async fn compute_next_flow_transform( itered_len: Some(itered_len), itered: Some(itered), }), + iteration_label, // we removed the is_simple_case for simple_input_transforms // if is_simple { // match value { @@ -6474,6 +6636,7 @@ async fn compute_next_flow_transform( branchall: Some(BranchAllStatus { branch: 0, len }), iterator: None, simple_input_transforms: None, + iteration_label: None, }, )); } else { @@ -6624,6 +6787,95 @@ async fn next_loop_iteration( )) } +const ITERATION_LABEL_MAX_CHARS: usize = 100; +const ITERATION_LABEL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2); +const ITERATION_LABELS_BUDGET: std::time::Duration = std::time::Duration::from_secs(10); + +/// One label per entry of `iters` (each an `iter` value). Labels are display-only: one that +/// throws or yields nothing is `None`. Labelling one push is bounded as a whole, and the first +/// label that runs out of time leaves the rest `None`, so a slow or hanging expression delays a +/// parallel loop by at most one budget rather than once per item. +async fn eval_iteration_labels( + label: &InputTransform, + iters: Vec<Box<RawValue>>, + flow_args: &HashMap<String, Box<RawValue>>, + flow_env: Option<&HashMap<String, Box<RawValue>>>, + client: &AuthedClient, + by_id: &IdContext, +) -> Vec<Option<String>> { + let n = iters.len(); + let deadline = std::time::Instant::now() + ITERATION_LABELS_BUDGET; + let mut labels = Vec::with_capacity(n); + for iter in iters { + let timeout = ITERATION_LABEL_TIMEOUT + .min(deadline.saturating_duration_since(std::time::Instant::now())); + if timeout.is_zero() { + tracing::warn!( + "iteration labels ran out of time, leaving the remaining iterations unlabelled" + ); + break; + } + let mut flow_input = flow_args.clone(); + insert_iter_arg(&mut flow_input, "iter".to_string(), iter); + let started = std::time::Instant::now(); + labels.push( + eval_iteration_label( + label, + timeout, + Marc::new(flow_input), + flow_env, + client, + by_id, + ) + .await, + ); + if started.elapsed() >= timeout { + tracing::warn!( + "iteration label timed out, leaving the remaining iterations unlabelled" + ); + break; + } + } + labels.resize(n, None); + labels +} + +async fn eval_iteration_label( + label: &InputTransform, + timeout: std::time::Duration, + flow_input: Marc<HashMap<String, Box<RawValue>>>, + flow_env: Option<&HashMap<String, Box<RawValue>>>, + client: &AuthedClient, + by_id: &IdContext, +) -> Option<String> { + let raw = match label { + InputTransform::Static { value } => value.clone(), + InputTransform::Javascript { expr } if !expr.trim().is_empty() => { + match eval_within(timeout, expr, flow_input, flow_env, client, by_id).await { + Ok(v) => v, + Err(e) => { + tracing::warn!("could not evaluate iteration label `{expr}`: {e:#}"); + return None; + } + } + } + _ => return None, + }; + let text = match serde_json::from_str::<serde_json::Value>(raw.get()).ok()? { + serde_json::Value::Null => return None, + serde_json::Value::String(s) => s, + v => v.to_string(), + }; + // jsonb rejects NUL, and the label lands in the flow status. + let text: String = text + .trim() + .chars() + .filter(|c| *c != '\0') + .take(ITERATION_LABEL_MAX_CHARS) + .collect(); + (!text.is_empty()).then_some(text) +} + pub(super) fn is_simple_modules( modules: &Vec<FlowModule>, failure_module: Option<&Box<FlowModule>>, @@ -6718,6 +6970,8 @@ async fn next_forloop_status( flow_jobs: vec![], flow_jobs_success: Some(vec![]), flow_jobs_duration: Some(FlowJobsDuration::new(0)), + flow_jobs_labels: None, + iteration_label: None, new_args: iter, while_loop: false, }) @@ -6731,6 +6985,7 @@ async fn next_forloop_status( flow_jobs: Some(flow_jobs), flow_jobs_success, flow_jobs_duration, + flow_jobs_labels, .. } if !*parallel => { // Read itered from separate table or fallback to JSONB @@ -6792,6 +7047,8 @@ async fn next_forloop_status( flow_jobs: flow_jobs.clone(), flow_jobs_success: flow_jobs_success.clone(), flow_jobs_duration: flow_jobs_duration.clone(), + flow_jobs_labels: flow_jobs_labels.clone(), + iteration_label: None, new_args: Iter { index: index as i32, value: next.to_owned() }, while_loop: false, }) @@ -7005,6 +7262,7 @@ pub async fn script_to_payload( let (jp, tag, delete_after_use, delete_after_secs, script_timeout, on_behalf_of) = script_path_to_payload( &script, + RunOrigin::Deployed, None, db.clone(), &flow_job.workspace_id, diff --git a/backend/windmill-worker/src/worker_lockfiles.rs b/backend/windmill-worker/src/worker_lockfiles.rs index 5769fd4196..e3642b15f3 100644 --- a/backend/windmill-worker/src/worker_lockfiles.rs +++ b/backend/windmill-worker/src/worker_lockfiles.rs @@ -664,7 +664,7 @@ pub async fn handle_dependency_job( "CI test trigger: checking for tests referencing script {}", script_path ); - { + if !arg_is_true(job.args.as_ref(), "skip_ci_tests") { let db2 = db.clone(); let w_id2 = w_id.to_string(); let script_path2 = script_path.to_string(); @@ -888,6 +888,7 @@ async fn requeue_relock( &job.permissioned_as, db, already_visited, + arg_is_true(job.args.as_ref(), "skip_ci_tests"), ) .await } @@ -1410,7 +1411,11 @@ pub async fn handle_flow_dependency_job( /// Set by a deploy someone made of a perpetual script, and by nothing else: a relock this path /// gets because an imported script changed leaves the runs of the version it replaces alone. fn restart_perpetual_runs_from_args(args: Option<&Json<HashMap<String, Box<RawValue>>>>) -> bool { - args.and_then(|args| args.0.get("restart_perpetual_runs")) + arg_is_true(args, "restart_perpetual_runs") +} + +fn arg_is_true(args: Option<&Json<HashMap<String, Box<RawValue>>>>, name: &str) -> bool { + args.and_then(|args| args.0.get(name)) .and_then(|value| serde_json::from_str::<bool>(value.get()).ok()) .unwrap_or(false) } @@ -1691,6 +1696,7 @@ async fn lock_modules( parallel, parallelism, squash, + iteration_label, } => { let nmodules; (nmodules, nmodified_ids, nerrors) = Box::pin(lock_modules( @@ -1723,6 +1729,7 @@ async fn lock_modules( parallel, parallelism, squash, + iteration_label, } .into() } diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 851a59e987..c8a3ed66c7 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.866.0"; +export const VERSION = "v1.880.1"; export async function login(email: string, password: string): Promise<string> { return await windmill.UserService.login({ diff --git a/chat-sdk/README.md b/chat-sdk/README.md index 711ec1a988..3ac051fd7e 100644 --- a/chat-sdk/README.md +++ b/chat-sdk/README.md @@ -245,6 +245,7 @@ interface ChatState { loadingMessages: boolean hasMoreMessages: boolean runningJobId?: string // the flow job the running turn follows + waitingOnBackground?: boolean // the agent answered and waits on tools running in the background } interface ChatMessage { @@ -267,8 +268,11 @@ A turn goes `submitted` (the flow is queued) → `streaming` (the answer is arri `success` or `error`. A flow that fails still completes the turn: its error is the answer, an `assistant` message with `success: false`. `status: 'error'` (with `error` set) means the turn could not run or be followed at all, such as a refused request. +An agent that answered while some of its tools still run in the background keeps its turn +`streaming` with `waitingOnBackground` set until one of them finishes and wakes it: its answer +is given, and those tools' messages stay `running` until their results arrive. -Methods: `sendMessage(text, { inputs?, attachments?, attachmentsInput? })`, `stop()`, +Methods: `sendMessage(text, { inputs?, attachments?, attachmentsInput?, overRunningTurn? })`, `stop()`, `newConversation()`, `selectConversation(id)`, `loadConversations({ page?, perPage?, kind? })`, `deleteConversation(id)`, `renameConversation(id, title)`, `loadOlderMessages()`, `resumeTurn(turn)`, `refreshMessages()` (reads what another tab added to the open @@ -276,7 +280,11 @@ conversation), `destroy()`. `kind` lists the flow editor's test chats (`'test'`) own (`'deployed'`, the server's default) or both (`'all'`); each `Conversation` carries `isTest`. A rename keeps the conversation's place in the list. Switching conversations stops following the current answer; the flow keeps running and, with server history, -its answer is there when you come back. +its answer is there when you come back. `overRunningTurn` sends while a turn is still +followed: the server takes the message when that turn's AI agent is parked (it answered while +background jobs run, or waits on an approval or a question), ending that turn and carrying its +background jobs over, and the chat follows the new one; while the turn works it is refused with a +`TurnRunningError` and the chat keeps following it. ## Attachments diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 69c3fa2b56..b855b97de2 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.866.0", + "version": "1.880.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.866.0", + "version": "1.880.1", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index be58d54c45..9324b0c74e 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.866.0", + "version": "1.880.1", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/chat-sdk/src/chat.ts b/chat-sdk/src/chat.ts index 69832d7ec7..3dd6118d79 100644 --- a/chat-sdk/src/chat.ts +++ b/chat-sdk/src/chat.ts @@ -62,6 +62,8 @@ interface Turn { /** Id of the streaming assistant message; cleared when a tool call ends the round. */ assistantId?: string streamedText: boolean + /** Sent over a running turn and stopped before the server answered: its run is cancelled. */ + stopped?: boolean } export function createChat<W extends RawAppWmill>(options: TypedChatOptions<W>): Chat { @@ -75,6 +77,8 @@ class ChatImpl implements Chat { readonly #listeners = new Set<(state: ChatState) => void>() #state: ChatState #turn: Turn | undefined + /** A message sent over the running turn, until the server takes or refuses it. */ + #sentOver: Turn | undefined #page = 1 /** The kind the caller last listed, so the refresh after a new turn lists the same rows. */ #conversationKind: ConversationKind | undefined @@ -130,9 +134,19 @@ class ChatImpl implements Chat { if (options.attachments?.length) throw new Error('windmill-chat: attachments need a message to go with them') return } - if (this.#turn) { + // Followed until the server takes this message, which it refuses while that turn works. + const running = this.#turn + if (running && !options.overRunningTurn) { throw new Error('windmill-chat: a message is already being answered; call stop() first') } + if (running && options.attachments?.length) { + throw new Error('windmill-chat: attachments cannot be sent over a running turn') + } + // One at a time, even once the turn it was sent over has ended: taken late, it would replace + // the turn sent meanwhile. `stop()` and leaving the conversation cancel the send still waiting. + if (this.#sentOver) { + throw new Error('windmill-chat: a message sent over the running turn is still waiting for the server') + } const attachments = options.attachments ?? [] const attachmentsInput = options.attachmentsInput if (attachments.length > 0 && !attachmentsInput) { @@ -156,8 +170,10 @@ class ChatImpl implements Chat { withdrawn: false, streamedText: false } - this.#turn = turn - this.#epoch++ + if (!running) { + this.#turn = turn + this.#epoch++ + } const timestamp = now() const conversation: Conversation = this.#state.conversations.find( @@ -170,8 +186,7 @@ class ChatImpl implements Chat { ...this.#state.messages, { id: turn.userMessageId, role: 'user', content, success: true, createdAt: timestamp, pending: true } ], - status: 'submitted', - error: undefined + ...(running ? {} : { status: 'submitted' as const, error: undefined }) }) try { @@ -200,15 +215,24 @@ class ChatImpl implements Chat { }) this.#rememberConversation() const context = { memoryId: conversationId, conversationId, signal: turn.controller.signal } + if (running) this.#sentOver = turn turn.jobId = this.#config.run ? await this.#config.run(args, context) : await this.#api.runFlow(this.#config.flowPath, args, context) + // Stopped or left while the server answered: a `run` that ignores the signal still + // returns its job, which a stop cancels and a switch leaves running unfollowed. + if (running && turn.controller.signal.aborted) { + if (turn.stopped && !this.#config.follow) await this.#api.cancelJob(turn.jobId).catch(() => {}) + throw abortError() + } } catch (e) { try { // Nothing of this message reached the server, whether the conversation was already // answering one sent elsewhere or an attachment never uploaded: the message is taken // back rather than shown as a failed turn, and the caller gets the reason. - if (e instanceof TurnRunningError || !turn.started) { + // Sent over a running turn, a message the server did not take goes back too: the turn + // on screen is that one, not this. + if (e instanceof TurnRunningError || !turn.started || running) { this.#withdrawTurn(turn) throw e } @@ -219,6 +243,28 @@ class ChatImpl implements Chat { } finally { if (this.#turn === turn) this.#turn = undefined } + } finally { + if (this.#sentOver === turn) this.#sentOver = undefined + } + if (running) { + // A conversation left meanwhile has the run go on unfollowed, like a turn it was showing. + if (this.#state.conversationId !== conversationId) return + // The server handed this message the conversation: what the old turn showed stays as it is. + if (this.#turn) this.#detachTurn() + this.#turn = turn + this.#epoch++ + const oldTurnStart = lastUserBefore(this.#state.messages, turn.userMessageId) + this.#set({ + // A call of the old turn still running in the background stays open, its row read or + // not: the new turn adopts its job and streams its result to it. + messages: this.#state.messages.map((m, j) => { + const running = m.role === 'tool' && m.tool?.status === 'running' + if (running) return j > oldTurnStart ? { ...m, pending: true } : m + return m.pending && m.id !== turn.userMessageId ? { ...m, pending: false } : m + }), + status: 'submitted', + error: undefined + }) } await this.#followTurn(turn, isNew) } @@ -328,12 +374,19 @@ class ChatImpl implements Chat { this.#failTurn(turn, e) } finally { if (this.#turn === turn) this.#turn = undefined - if (this.#state.runningJobId === turn.jobId) this.#set({ runningJobId: undefined }) + if (this.#state.runningJobId === turn.jobId) { + this.#set({ runningJobId: undefined, waitingOnBackground: undefined }) + } } if (nextTurn) await this.resumeTurn(nextTurn) } stop = async (): Promise<void> => { + const sentOver = this.#sentOver + if (sentOver) { + sentOver.stopped = true + sentOver.controller.abort() + } const turn = this.#turn if (!turn) return this.#detachTurn() @@ -644,15 +697,21 @@ class ChatImpl implements Chat { patch: Partial<ToolInvocation> & { content?: string; success?: boolean } ) => { const { content, success, ...toolPatch } = patch - // Only this turn's tool messages are pending; a provider may reuse call ids across turns. + // Only this turn's: a provider may reuse call ids across turns. Those are the pending + // ones and those past the latest question, which a mid-turn row read settles while the + // call still waits on its background job. + let asked = messages.length - 1 + while (asked >= 0 && messages[asked].role !== 'user') asked-- const i = messages.findIndex( - (m) => m.pending && m.role === 'tool' && m.tool?.callId === callId + (m, j) => (m.pending || j > asked) && m.role === 'tool' && m.tool?.callId === callId ) if (i >= 0) { const existing = messages[i] messages[i] = { ...existing, - content: content ?? existing.content, + // A stored row keeps its text: one that says the call went to the background is what + // its later result row is matched to. + content: existing.seq === undefined ? content ?? existing.content : existing.content, success: success ?? existing.success, tool: { ...existing.tool!, ...toolPatch } } @@ -697,7 +756,10 @@ class ChatImpl implements Chat { }) } } + // Anything the agent streams after it means it woke up. + let waitingOnBackground = false for (const event of events) { + waitingOnBackground = event.type === 'background_wait' switch (event.type) { case 'token_delta': turn.streamedText = true @@ -729,7 +791,17 @@ class ChatImpl implements Chat { break } } - this.#set({ messages, status: 'streaming' }) + const startsWaiting = waitingOnBackground && !this.#state.waitingOnBackground + this.#set({ messages, status: 'streaming', waitingOnBackground }) + // Rows are otherwise read when the turn ends, which a wait on background jobs postpones; the + // rows of the calls it waits on are written by then, and say how each went to the background. + if (startsWaiting && this.#state.history === 'server') { + this.#rowsAfterLastSeq(turn.conversationId, turn.controller.signal) + .then((rows) => { + if (this.#turnActive(turn)) this.#mergeRows(rows) + }) + .catch(() => {}) + } } async #finishTurn(turn: Turn, result: unknown, isNew: boolean): Promise<RunningTurn | undefined> { @@ -977,8 +1049,15 @@ class ChatImpl implements Chat { for (const row of rows.map(fromRow)) { if (known.has(row.id)) continue known.add(row.id) + // The result of a call whose background start is already held is that call's own row: + // matched by tool name, it would take a later call of the same tool's place. + const backgroundResult = + row.role === 'tool' && + row.jobId !== undefined && + messages.some((m) => m.seq !== undefined && m.jobId === row.jobId && BACKGROUND_START.test(m.content)) let i = messages.findIndex( (m) => + !backgroundResult && m.seq === undefined && m.role === row.role && (m.content === row.content || (row.tool !== undefined && m.tool?.name === row.tool.name)) @@ -996,9 +1075,13 @@ class ChatImpl implements Chat { } if (i >= 0) { const m = messages[i] + // A row saying the call went to the background, read after its result streamed in, + // does not set it running again nor undo how it went. + const outrun = row.tool?.status === 'running' && !!m.tool && m.tool.status !== 'running' messages[i] = { ...row, id: m.id, + success: outrun ? m.success : row.success, reasoning: m.reasoning ?? row.reasoning, // The stream's call wins where it has a value; a stream cut short leaves gaps the row fills. tool: @@ -1007,7 +1090,7 @@ class ChatImpl implements Chat { ...m.tool, arguments: m.tool.arguments ?? row.tool?.arguments, result: m.tool.result ?? row.tool?.result, - status: row.tool?.status ?? m.tool.status + status: outrun ? m.tool.status : (row.tool?.status ?? m.tool.status) } : row.tool } @@ -1104,6 +1187,7 @@ class ChatImpl implements Chat { */ #leaveConversation(): void { this.#epoch++ + this.#sentOver?.controller.abort() if (this.#turn) { this.#detachTurn() this.#set({ messages: finalized(this.#state.messages), status: 'idle' }) @@ -1135,10 +1219,21 @@ function latestSeq(messages: readonly ChatMessage[]): number { return messages.reduce((newest, m) => (m.seq !== undefined && m.seq > newest ? m.seq : newest), 0) } +const BACKGROUND_START = /^(?:Started (.+) in the background|Moved (.+) to the background(?: after \d+s)?)$/ + function fromRow(row: FlowConversationMessage): ChatMessage { + // A call that went to the background: its result comes as a later row of the same job. + const background = + row.message_type === 'tool' + ? BACKGROUND_START.exec(row.content) + ?.slice(1) + .find((name) => name !== undefined) + : undefined const toolName = row.message_type === 'tool' - ? /^Used (.+) tool$/.exec(row.content)?.[1] ?? /^Error executing (.+)$/.exec(row.content)?.[1] + ? /^Used (.+) tool$/.exec(row.content)?.[1] ?? + /^Error executing (.+)$/.exec(row.content)?.[1] ?? + background : undefined const success = row.success ?? true return { @@ -1160,7 +1255,7 @@ function fromRow(row: FlowConversationMessage): ChatMessage { tool: toolName ? { name: toolName, - status: success ? 'success' : 'error', + status: background ? 'running' : success ? 'success' : 'error', arguments: row.tool_arguments ?? undefined, result: row.tool_result ?? undefined } @@ -1193,6 +1288,14 @@ function assistantMessage(content: string, success: boolean, jobId: string | und } } +/** Index of the latest user message before the one with `id`, the start of the turn it ends. */ +function lastUserBefore(messages: readonly ChatMessage[], id: string): number { + let j = messages.findIndex((m) => m.id === id) + if (j < 0) j = messages.length + while (--j >= 0 && messages[j].role !== 'user') {} + return j +} + function finalized(messages: ChatMessage[]): ChatMessage[] { return messages.some((m) => m.pending) ? messages.map((m) => (m.pending ? { ...m, pending: false } : m)) diff --git a/chat-sdk/src/stream.ts b/chat-sdk/src/stream.ts index c6969bb7b4..7d7287618d 100644 --- a/chat-sdk/src/stream.ts +++ b/chat-sdk/src/stream.ts @@ -12,8 +12,11 @@ export type AgentStreamEvent = result: string success: boolean } + /** The agent answered and waits on tools still running in the background. */ + | { type: 'background_wait' } const KNOWN_TYPES = new Set([ + 'background_wait', 'token_delta', 'reasoning_token_delta', 'tool_call', diff --git a/chat-sdk/src/types.ts b/chat-sdk/src/types.ts index 155b0bfacd..722b9b398f 100644 --- a/chat-sdk/src/types.ts +++ b/chat-sdk/src/types.ts @@ -82,6 +82,12 @@ export interface ChatState { hasMoreMessages: boolean /** The flow job the running turn follows, once it is known. */ runningJobId?: string + /** + * The running turn's AI agent has answered and waits, without a worker, on tools still running + * in the background: nothing streams until one finishes. Set by its `background_wait` event, + * cleared by the next event and when the turn ends. + */ + waitingOnBackground?: boolean } export type TokenSource = string | (() => string | Promise<string>) @@ -196,6 +202,15 @@ export interface SendMessageOptions { attachments?: AttachmentUpload[] /** Required with `attachments`, which also need message text. With `multiple: false`, more than one attachment is refused before anything uploads. */ attachmentsInput?: AttachmentsInput + /** + * Send although the chat is still following a turn. The server takes the message when that + * turn's AI agent is parked (it answered while background jobs run, or waits on an approval or + * a question): it ends that turn, dropping its open request, and carries its background jobs + * over to this one, which the chat then follows. While the turn works it is refused with a + * `TurnRunningError` and the chat keeps following it. Not with `attachments`, and one at a time: + * a second one is refused while the first waits for the server. + */ + overRunningTurn?: boolean } export interface Chat { diff --git a/chat-sdk/test/chat.test.ts b/chat-sdk/test/chat.test.ts index 6c88af5a36..9d9cbdc0a4 100644 --- a/chat-sdk/test/chat.test.ts +++ b/chat-sdk/test/chat.test.ts @@ -26,6 +26,34 @@ function options(extra: Partial<ChatOptions>, fetch: ChatOptions['fetch']): Chat } describe('createChat with local history', () => { + test('marks a turn waiting on background tools until the agent streams again', async () => { + const { fetch } = fetchMock(run, (c) => + c.url.pathname === streamPath + ? sseTimed([ + { + type: 'update', + new_result_stream: ndjson({ type: 'token_delta', content: 'On it' }, { type: 'background_wait' }), + stream_offset: 1 + }, + 200, + { + type: 'update', + new_result_stream: ndjson({ type: 'token_delta', content: ' and done' }), + stream_offset: 2, + completed: true, + only_result: { windmill_chat_answer: 'On it and done' } + } + ]) + : undefined + ) + const chat = createChat(options({}, fetch)) + const sent = chat.sendMessage('go') + await until(() => chat.getState().waitingOnBackground === true, 'the background wait') + expect(chat.getState().status).toBe('streaming') + await sent + expect(chat.getState().waitingOnBackground).toBeFalsy() + }) + test('streams text and tool calls, then finalizes and persists the turn', async () => { const storage = memoryStorage() const { fetch, calls } = fetchMock(run, (c) => @@ -955,6 +983,376 @@ describe('createChat with server history', () => { ]) }) + describe('sent over a running turn', () => { + // The first turn answers, then stays open the way a parked agent's run does. + const running = (second: () => Response): Route[] => { + let runs = 0 + return [ + (c) => + c.method === 'POST' && c.url.pathname === `/api/w/ws/jobs/run/f/${FLOW}` + ? ++runs === 1 + ? text('job-1') + : second() + : undefined, + (c) => + c.url.pathname === streamPath + ? sseTimed([ + { type: 'update', new_result_stream: ndjson({ type: 'token_delta', content: 'parked answer' }), stream_offset: 1 }, + 3000 + ]) + : undefined + ] + } + + test('keeps following that turn when the server refuses the message', async () => { + const { fetch } = fetchMock( + ...running(() => text(JSON.stringify({ error: 'still answering', running_turn: { job_id: 'job-1', user_seq: 1 } }), 409)) + ) + const chat = createChat(options({}, fetch)) + void chat.sendMessage('first') + await until(() => chat.getState().messages.some((m) => m.content === 'parked answer'), 'the first answer') + const refused = await chat.sendMessage('more', { overRunningTurn: true }).catch((e) => e) + expect(refused).toBeInstanceOf(TurnRunningError) + const state = chat.getState() + expect(state.messages.map((m) => m.content)).toEqual(['first', 'parked answer']) + expect(state.status).toBe('streaming') + expect(state.runningJobId).toBe('job-1') + chat.destroy() + }) + + test('Stop while the server answers cancels the new run instead of following it', async () => { + let answer = (_r: Response) => {} + const { fetch, calls } = fetchMock( + ...running(() => { + throw new Error('unused') + }).slice(1), + (c) => { + if (c.method !== 'POST' || c.url.pathname !== `/api/w/ws/jobs/run/f/${FLOW}`) return undefined + return calls.filter((x) => x.url.pathname === c.url.pathname).length === 1 + ? text('job-1') + : // Answered only after Stop, the way a request already on the wire is. + (new Promise<Response>((resolve) => (answer = resolve)) as unknown as Response) + }, + (c) => (c.url.pathname.includes('/jobs_u/queue/cancel/') ? text('cancelled') : undefined) + ) + const chat = createChat(options({}, fetch)) + void chat.sendMessage('first') + await until(() => chat.getState().messages.some((m) => m.content === 'parked answer'), 'the first answer') + const sent = chat.sendMessage('more', { overRunningTurn: true }).catch((e) => e) + await until(() => chat.getState().messages.some((m) => m.content === 'more'), 'the message sent') + await chat.stop() + answer(text('job-2')) + expect(await sent).toBeInstanceOf(Error) + const state = chat.getState() + expect(state.status).toBe('idle') + expect(state.messages.map((m) => m.content)).toEqual(['first', 'parked answer']) + expect(calls.some((c) => c.url.pathname.endsWith('/jobs_u/queue/cancel/job-2'))).toBe(true) + chat.destroy() + }) + + test('refuses a second message over the running turn while the first waits for the server', async () => { + const { fetch } = fetchMock( + ...running(() => new Promise<Response>(() => {}) as unknown as Response) + ) + const chat = createChat(options({}, fetch)) + void chat.sendMessage('first') + await until(() => chat.getState().messages.some((m) => m.content === 'parked answer'), 'the first answer') + void chat.sendMessage('one', { overRunningTurn: true }).catch(() => {}) + await until(() => chat.getState().messages.some((m) => m.content === 'one'), 'the first send') + const second = await chat.sendMessage('two', { overRunningTurn: true }).catch((e) => e) + expect(second).toBeInstanceOf(Error) + expect(chat.getState().messages.map((m) => m.content)).toEqual(['first', 'parked answer', 'one']) + chat.destroy() + }) + + test('refuses another message while one sent over a turn that has since ended waits', async () => { + let runs = 0 + const { fetch } = fetchMock( + (c) => + c.method === 'POST' && c.url.pathname === `/api/w/ws/jobs/run/f/${FLOW}` + ? ++runs === 1 + ? text('job-1') + : (new Promise<Response>(() => {}) as unknown as Response) + : undefined, + (c) => + c.url.pathname === streamPath + ? sseTimed([ + { type: 'update', new_result_stream: ndjson({ type: 'token_delta', content: 'parked answer' }), stream_offset: 1 }, + 300, + { type: 'update', completed: true, only_result: { windmill_chat_answer: 'parked answer' } } + ]) + : undefined + ) + const chat = createChat(options({}, fetch)) + const first = chat.sendMessage('first') + await until(() => chat.getState().messages.some((m) => m.content === 'parked answer'), 'the first answer') + void chat.sendMessage('one', { overRunningTurn: true }).catch(() => {}) + await first + expect(chat.getState().status).toBe('idle') + const another = await chat.sendMessage('two').catch((e) => e) + expect(another).toBeInstanceOf(Error) + chat.destroy() + }) + + test('a background call whose row was read stays open for the new turn to fill', async () => { + let runs = 0 + const { fetch } = fetchMock( + (c) => + c.method === 'POST' && c.url.pathname === `/api/w/ws/jobs/run/f/${FLOW}` + ? text(++runs === 1 ? 'job-1' : 'job-2') + : undefined, + (c) => + c.url.pathname === streamPath + ? sseTimed([ + { + type: 'update', + new_result_stream: ndjson( + { type: 'tool_call', call_id: 'c1', function_name: 'export' }, + { type: 'background_wait' } + ), + stream_offset: 2 + }, + 3000 + ]) + : undefined, + (c) => + c.url.pathname === '/api/w/ws/jobs_u/getupdate_sse/job-2' + ? sseTimed([ + 200, + { + type: 'update', + new_result_stream: ndjson({ + type: 'tool_result', + call_id: 'c1', + function_name: 'export', + result: '"ok"', + success: true + }), + stream_offset: 1, + completed: true, + only_result: { windmill_chat_answer: 'second answer' } + } + ]) + : undefined, + (c) => + c.method === 'GET' && c.url.pathname.endsWith('/messages') + ? json([ + messageRow(1, 'user', 'first'), + messageRow(2, 'tool', 'Moved export to the background after 5s', { job_id: 'bg-1' }) + ]) + : undefined + ) + const chat = createChat(options({}, fetch)) + void chat.sendMessage('first') + await until( + () => chat.getState().messages.some((m) => m.seq === 2 && m.tool?.callId === 'c1'), + 'the background row read' + ) + await chat.sendMessage('more', { overRunningTurn: true }) + await until(() => chat.getState().status === 'idle', 'the new turn') + const tools = chat.getState().messages.filter((m) => m.role === 'tool') + expect(tools.map((m) => [m.tool?.callId, m.tool?.status, m.tool?.result])).toEqual([['c1', 'success', '"ok"']]) + chat.destroy() + }) + + test('follows the new turn when the server takes the message', async () => { + const { fetch } = fetchMock(...running(() => text('job-2')), (c) => + c.url.pathname === '/api/w/ws/jobs_u/getupdate_sse/job-2' + ? sse([{ type: 'update', completed: true, only_result: { windmill_chat_answer: 'second answer' } }]) + : undefined + ) + const chat = createChat(options({}, fetch)) + void chat.sendMessage('first') + await until(() => chat.getState().messages.some((m) => m.content === 'parked answer'), 'the first answer') + await chat.sendMessage('more', { overRunningTurn: true }) + const state = chat.getState() + expect(state.messages.map((m) => [m.content, !!m.pending])).toEqual([ + ['first', false], + ['parked answer', false], + ['more', false], + ['second answer', false] + ]) + expect(state.status).toBe('idle') + chat.destroy() + }) + }) + + test('reads a row of a call that went to the background as a call of that tool', async () => { + const { fetch } = fetchMock((c) => + c.url.pathname.endsWith('/messages') + ? json([ + messageRow(1, 'user', 'go'), + messageRow(2, 'tool', 'Started report in the background', { job_id: 'bg-1' }), + messageRow(3, 'tool', 'Moved export to the background after 5s', { job_id: 'bg-2' }) + ]) + : undefined + ) + const chat = createChat(options({}, fetch)) + await chat.selectConversation('conv') + expect(chat.getState().messages.map((m) => m.tool?.name)).toEqual([undefined, 'report', 'export']) + }) + + test.each([true, false])('a row read after a background result streamed in keeps how it went (success: %p)', async (success) => { + let reads = 0 + const { fetch } = fetchMock( + run, + (c) => + c.url.pathname === streamPath + ? sseTimed([ + { + type: 'update', + new_result_stream: ndjson( + { type: 'tool_call', call_id: 'c1', function_name: 'export' }, + { type: 'background_wait' } + ), + stream_offset: 2 + }, + 50, + { + type: 'update', + new_result_stream: ndjson({ + type: 'tool_result', + call_id: 'c1', + function_name: 'export', + result: '"ok"', + success + }), + stream_offset: 3 + }, + 600, + { + type: 'update', + new_result_stream: ndjson({ type: 'token_delta', content: 'Done' }), + stream_offset: 4, + completed: true, + only_result: { output: 'Done', messages: [] } + } + ]) + : undefined, + async (c) => { + if (c.method !== 'GET' || !c.url.pathname.endsWith('/messages')) return undefined + // The read the wait starts answers after the result streamed in. + if (reads++ === 0) await new Promise((resolve) => setTimeout(resolve, 300)) + return json([ + messageRow(1, 'user', 'go'), + messageRow(2, 'tool', 'Moved export to the background after 5s', { job_id: 'bg-1' }) + ]) + } + ) + const chat = createChat(options({}, fetch)) + const sent = chat.sendMessage('go') + await until(() => reads > 0, 'the read') + await new Promise((resolve) => setTimeout(resolve, 450)) + const call = chat.getState().messages.find((m) => m.role === 'tool') + expect([call?.content, call?.tool?.status, call?.success]).toEqual([ + 'Moved export to the background after 5s', + success ? 'success' : 'error', + success + ]) + await sent + }) + + test('a background result streams onto the card its row was read into while waiting', async () => { + let waited = false + const { fetch } = fetchMock( + run, + (c) => + c.url.pathname === streamPath + ? sseTimed([ + { + type: 'update', + new_result_stream: ndjson( + { type: 'tool_call', call_id: 'c1', function_name: 'export' }, + { type: 'background_wait' } + ), + stream_offset: 2 + }, + 100, + { + type: 'update', + new_result_stream: ndjson( + { type: 'tool_result', call_id: 'c1', function_name: 'export', result: '"ok"', success: true }, + { type: 'token_delta', content: 'Done' } + ), + stream_offset: 4, + completed: true, + only_result: { output: 'Done', messages: [] } + } + ]) + : undefined, + (c) => { + if (c.method !== 'GET' || !c.url.pathname.endsWith('/messages')) return undefined + if (!waited) { + waited = true + return json([ + messageRow(1, 'user', 'go'), + messageRow(2, 'tool', 'Moved export to the background after 5s', { job_id: 'bg-1' }) + ]) + } + return json([ + messageRow(1, 'user', 'go'), + messageRow(2, 'tool', 'Moved export to the background after 5s', { job_id: 'bg-1' }), + messageRow(3, 'tool', 'Used export tool', { job_id: 'bg-1', tool_result: '"ok"' }), + messageRow(4, 'assistant', 'Done') + ]) + } + ) + const chat = createChat(options({}, fetch)) + await chat.sendMessage('go') + // The call's card, filled by the stream and still worded as its row, then the result's row, + // which a display folds into that card by job. + const tools = chat.getState().messages.filter((m) => m.role === 'tool') + expect(tools.map((m) => [m.content, m.tool?.callId, m.tool?.result])).toEqual([ + ['Moved export to the background after 5s', 'c1', '"ok"'], + ['Used export tool', undefined, '"ok"'] + ]) + }) + + test('repeated background calls of one tool each keep their own result', async () => { + const call = (id: string) => ({ type: 'tool_call', call_id: id, function_name: 'export' }) + const result = (id: string, r: string) => ({ + type: 'tool_result', + call_id: id, + function_name: 'export', + result: r, + success: true + }) + const { fetch } = fetchMock( + run, + (c) => + c.url.pathname === streamPath + ? sse([ + { + type: 'update', + new_result_stream: ndjson(call('c1'), result('c1', '"A"'), call('c2'), result('c2', '"B"')), + stream_offset: 4, + completed: true, + only_result: { output: 'Done', messages: [] } + } + ]) + : undefined, + (c) => + c.method === 'GET' && c.url.pathname.endsWith('/messages') + ? json([ + messageRow(1, 'user', 'go'), + messageRow(2, 'tool', 'Started export in the background', { job_id: 'bg-1' }), + messageRow(3, 'tool', 'Used export tool', { job_id: 'bg-1', tool_result: '"A"' }), + messageRow(4, 'tool', 'Started export in the background', { job_id: 'bg-2' }), + messageRow(5, 'tool', 'Used export tool', { job_id: 'bg-2', tool_result: '"B"' }) + ]) + : undefined + ) + const chat = createChat(options({}, fetch)) + await chat.sendMessage('go') + const tools = chat.getState().messages.filter((m) => m.role === 'tool') + expect(tools.map((m) => [m.jobId, m.tool?.callId, m.tool?.result])).toEqual([ + ['bg-1', 'c1', '"A"'], + ['bg-1', undefined, '"A"'], + ['bg-2', 'c2', '"B"'], + ['bg-2', undefined, '"B"'] + ]) + }) + test('a message refused because a turn is running leaves nothing behind and names that turn', async () => { const { fetch } = fetchMock( (c) => diff --git a/chat-sdk/test/support.ts b/chat-sdk/test/support.ts index e198f19355..208348320f 100644 --- a/chat-sdk/test/support.ts +++ b/chat-sdk/test/support.ts @@ -10,7 +10,7 @@ export interface RecordedCall { signal?: AbortSignal } -export type Route = (call: RecordedCall) => Response | Promise<Response> | undefined +export type Route = (call: RecordedCall) => Response | undefined | Promise<Response | undefined> /** A fetch whose responses come from the first route that answers; every call is recorded. */ export function fetchMock(...routes: Route[]): { fetch: FetchLike; calls: RecordedCall[] } { diff --git a/cli/bun.lock b/cli/bun.lock index 5c39e7e9df..3971fd8b81 100644 --- a/cli/bun.lock +++ b/cli/bun.lock @@ -14,7 +14,7 @@ "esbuild": "0.28.2", "get-port": "7.1.0", "jszip": "3.8.0", - "minimatch": "^10.0.0", + "minimatch": "^11.0.1", "open": "^10.0.0", "pg-gateway": "0.3.0-beta.4", "svelte": "^5.56.8", @@ -35,7 +35,7 @@ "windmill-parser-wasm-yaml": "1.770.0", "windmill-yaml-validator": "1.1.1", "ws": "8.21.3", - "yaml": "^2.7.0", + "yaml": "^2.9.1", }, "devDependencies": { "@types/bun": "^1.3.9", @@ -44,6 +44,7 @@ "@types/tar-stream": "^3.1.4", "@types/ws": "^8.5.0", "ajv": "^8.17.1", + "tailwindcss": "4.1.14", "typescript": "^5.7.0", }, }, @@ -109,6 +110,8 @@ "@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="], + "@isaacs/nonrecursive-glob-match": ["@isaacs/nonrecursive-glob-match@1.1.0", "", {}, "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw=="], + "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="], "@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="], @@ -191,7 +194,7 @@ "bare-events": ["bare-events@2.8.2", "", { "peerDependencies": { "bare-abort-controller": "*" }, "optionalPeers": ["bare-abort-controller"] }, "sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ=="], - "brace-expansion": ["brace-expansion@5.0.2", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw=="], + "brace-expansion": ["brace-expansion@5.0.12", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="], "bun-types": ["bun-types@1.3.9", "", { "dependencies": { "@types/node": "*" } }, "sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg=="], @@ -223,7 +226,7 @@ "fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="], - "fast-uri": ["fast-uri@3.1.4", "", {}, "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw=="], + "fast-uri": ["fast-uri@3.1.9", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="], "get-port": ["get-port@7.1.0", "", {}, "sha512-QB9NKEeDg3xxVwCCwJQ9+xycaz6pBB6iQ76wiWMl1927n0Kir6alPiP+yuiICLLU4jpMe08dXfpebuQppFA2zw=="], @@ -251,7 +254,7 @@ "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], - "minimatch": ["minimatch@10.2.2", "", { "dependencies": { "brace-expansion": "^5.0.2" } }, "sha512-+G4CpNBxa5MprY+04MbgOw1v7So6n5JY166pFi9KfYwT78fxScCeSNQSNzp6dpPSW2rONOps6Ocam1wFhCgoVw=="], + "minimatch": ["minimatch@11.0.7", "", { "dependencies": { "@isaacs/nonrecursive-glob-match": "^1.1.0", "brace-expansion": "^5.0.12" } }, "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg=="], "open": ["open@10.2.0", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="], @@ -277,6 +280,8 @@ "svelte": ["svelte@5.56.8", "", { "dependencies": { "@jridgewell/remapping": "^2.3.4", "@jridgewell/sourcemap-codec": "^1.5.0", "@sveltejs/acorn-typescript": "^1.0.10", "@types/estree": "^1.0.5", "@types/trusted-types": "^2.0.7", "acorn": "^8.12.1", "aria-query": "5.3.1", "axobject-query": "^4.1.0", "clsx": "^2.1.1", "devalue": "^5.8.1", "esm-env": "^1.2.1", "esrap": "^2.2.12", "is-reference": "^3.0.3", "locate-character": "^3.0.0", "magic-string": "^0.30.11", "zimmerframe": "^1.1.2" } }, "sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg=="], + "tailwindcss": ["tailwindcss@4.1.14", "", {}, "sha512-b7pCxjGO98LnxVkKjaZSDeNuljC4ueKUddjENJOADtubtdo8llTaJy7HwBMeLNSSo2N5QIAgklslK1+Ir8r6CA=="], + "tar-stream": ["tar-stream@3.1.7", "", { "dependencies": { "b4a": "^1.6.4", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ=="], "text-decoder": ["text-decoder@1.2.7", "", { "dependencies": { "b4a": "^1.6.4" } }, "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ=="], @@ -325,7 +330,7 @@ "wsl-utils": ["wsl-utils@0.1.0", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="], - "yaml": ["yaml@2.8.2", "", { "bin": "bin.mjs" }, "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A=="], + "yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], "zimmerframe": ["zimmerframe@1.1.4", "", {}, "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ=="], } diff --git a/cli/cursor b/cli/cursor deleted file mode 120000 index 80be7b6b55..0000000000 --- a/cli/cursor +++ /dev/null @@ -1 +0,0 @@ -/usr/bin/cursor \ No newline at end of file diff --git a/cli/package.json b/cli/package.json index 47dc820f9a..c153253171 100644 --- a/cli/package.json +++ b/cli/package.json @@ -27,7 +27,7 @@ "esbuild": "0.28.2", "get-port": "7.1.0", "jszip": "3.8.0", - "minimatch": "^10.0.0", + "minimatch": "^11.0.1", "open": "^10.0.0", "pg-gateway": "0.3.0-beta.4", "svelte": "^5.56.8", @@ -48,7 +48,7 @@ "windmill-parser-wasm-yaml": "1.770.0", "windmill-yaml-validator": "1.1.1", "ws": "8.21.3", - "yaml": "^2.7.0" + "yaml": "^2.9.1" }, "devDependencies": { "@types/bun": "^1.3.9", @@ -57,6 +57,7 @@ "@types/tar-stream": "^3.1.4", "@types/ws": "^8.5.0", "ajv": "^8.17.1", + "tailwindcss": "4.1.14", "typescript": "^5.7.0" } } diff --git a/cli/src/commands/app/bundle.ts b/cli/src/commands/app/bundle.ts index 1a2f1851f8..f99aba58a7 100644 --- a/cli/src/commands/app/bundle.ts +++ b/cli/src/commands/app/bundle.ts @@ -9,6 +9,7 @@ import { colors } from "@cliffy/ansi/colors"; import * as windmillUtils from "@windmill-labs/shared-utils"; import { readTextFile, readTextFileSync } from "../../utils/utils.ts"; import { withEsbuild } from "../../utils/esbuild_loader.ts"; +import { createTailwindPlugin } from "./tailwind.ts"; export interface BundleOptions { entryPoint?: string; outDir?: string; @@ -244,9 +245,13 @@ function createSveltePlugin(appDir: string): any { } /** - * Creates framework-specific esbuild plugins based on detected dependencies + * Creates framework-specific esbuild plugins based on detected dependencies. + * `sharedUiDir` is scanned for Tailwind class names alongside the app. */ -export async function createFrameworkPlugins(appDir: string): Promise<any[]> { +export async function createFrameworkPlugins( + appDir: string, + sharedUiDir?: string +): Promise<any[]> { const frameworks = detectFrameworks(appDir); const plugins: any[] = []; @@ -255,6 +260,9 @@ export async function createFrameworkPlugins(appDir: string): Promise<any[]> { plugins.push(createSveltePlugin(appDir)); } + const tailwind = createTailwindPlugin(appDir, sharedUiDir); + if (tailwind) plugins.push(tailwind); + return plugins; } @@ -393,8 +401,13 @@ export async function createBundle( // Ensure node_modules exists in the app directory await ensureNodeModules(appDir); - // Load framework-specific plugins (svelte) based on package.json - const frameworkPlugins = await createFrameworkPlugins(appDir); + const sharedUiDir = + options.sharedUiDir && fs.existsSync(options.sharedUiDir) + ? options.sharedUiDir + : undefined; + + // Load framework-specific plugins (svelte, tailwind) based on package.json + const frameworkPlugins = await createFrameworkPlugins(appDir, sharedUiDir); // Ensure output directory exists const distDir = path.join(process.cwd(), outDir); @@ -439,10 +452,9 @@ export async function createBundle( }, }; - const sharedUiPlugins: any[] = - options.sharedUiDir && fs.existsSync(options.sharedUiDir) - ? [createSharedUiPlugin(options.sharedUiDir, appDir)] - : []; + const sharedUiPlugins: any[] = sharedUiDir + ? [createSharedUiPlugin(sharedUiDir, appDir)] + : []; const buildOptions = { ...DEFAULT_BUILD_OPTIONS, diff --git a/cli/src/commands/app/dev.ts b/cli/src/commands/app/dev.ts index 6ff39462b5..11fb5793bd 100644 --- a/cli/src/commands/app/dev.ts +++ b/cli/src/commands/app/dev.ts @@ -592,14 +592,16 @@ async function dev(opts: DevOptions, appFolder?: string) { const buildOptions = getDevBuildOptions(entryPoint, frameworks.svelte); - // Load framework-specific plugins (svelte) based on package.json - const frameworkPlugins = await createFrameworkPlugins(appDir); + const foundUiDir = findSharedUiDir(appDir); + const sharedUiDir = + foundUiDir && fs.existsSync(foundUiDir) ? foundUiDir : undefined; - const sharedUiDir = findSharedUiDir(appDir); - const sharedUiPlugins = - sharedUiDir && fs.existsSync(sharedUiDir) - ? [createSharedUiPlugin(sharedUiDir, appDir)] - : []; + // Load framework-specific plugins (svelte, tailwind) based on package.json + const frameworkPlugins = await createFrameworkPlugins(appDir, sharedUiDir); + + const sharedUiPlugins = sharedUiDir + ? [createSharedUiPlugin(sharedUiDir, appDir)] + : []; const wmillPlugin = { name: "wmill-virtual", diff --git a/cli/src/commands/app/tailwind.ts b/cli/src/commands/app/tailwind.ts new file mode 100644 index 0000000000..0af5a0db6e --- /dev/null +++ b/cli/src/commands/app/tailwind.ts @@ -0,0 +1,244 @@ +import * as fs from "node:fs"; +import * as path from "node:path"; +import { createRequire } from "node:module"; +import { pathToFileURL } from "node:url"; +import * as log from "../../core/log.ts"; +import { colors } from "@cliffy/ansi/colors"; +import { readTextFileSync } from "../../utils/utils.ts"; +import { APP_BACKEND_FOLDER } from "./app_metadata.ts"; +import { + compileTailwind, + declaresTailwindV4, + installedTailwindMajor, + staticPrefix, + TAILWIND_SOURCE_EXTENSIONS, + type TailwindCompile, + type TailwindHost, + type TailwindSource, +} from "./tailwind_core.ts"; + +const MAX_SOURCE_BYTES = 1024 * 1024; + +/** `src/**\/*.vue` scans `.vue` files; a pattern naming no extension scans the default set. */ +function sourceExtensions(pattern: string): string[] { + const ext = pattern.match(/\*(\.[\w-]+)$/); + return ext ? [ext[1]] : TAILWIND_SOURCE_EXTENSIONS; +} + +function mtimeOf(file: string): number | undefined { + try { + return fs.statSync(file).mtimeMs; + } catch { + return undefined; + } +} + +function readJson(file: string): string | undefined { + try { + return readTextFileSync(file); + } catch { + return undefined; + } +} + +/** + * Walks `dir` for scannable files. The default walk skips build output + * (`dist`); an explicit `@source` keeps it, since a component library + * (`@source "../node_modules/some-ui-lib"`) ships its classes only there. + * Neither descends into a nested `node_modules`. + */ +function walk( + dir: string, + extensions: string[], + skipTop: Set<string>, + out: { files: Map<string, string>; dirs: Set<string> }, + explicit: boolean, +) { + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + out.dirs.add(dir); + for (const entry of entries) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) { + if (entry.name.startsWith(".") || skipTop.has(entry.name)) continue; + if (entry.name === "node_modules" || (!explicit && entry.name === "dist")) continue; + walk(full, extensions, new Set(), out, explicit); + } else if (entry.isFile()) { + if (!extensions.includes(path.extname(entry.name))) continue; + addFile(full, out); + } + } +} + +function addFile(file: string, out: { files: Map<string, string> }) { + let real: string; + try { + real = fs.realpathSync(file); + if (out.files.has(real) || fs.statSync(real).size > MAX_SOURCE_BYTES) return; + out.files.set(real, fs.readFileSync(real, "utf-8")); + } catch { + // A file that vanished mid-walk has no classes to contribute. + } +} + +/** + * The esbuild plugin compiling Tailwind CSS v4 stylesheets, or undefined when + * the app does not declare `tailwindcss` v4+: then nothing is registered and + * the build is exactly what it is without Tailwind. The compiler is the app's + * own, loaded on the first stylesheet that uses a Tailwind directive. + */ +export function createTailwindPlugin(appDir: string, sharedUiDir?: string): any | undefined { + const resolvedApp = path.resolve(appDir); + if (!declaresTailwindV4(readJson(path.join(resolvedApp, "package.json")))) { + return undefined; + } + const requireFromApp = createRequire(path.join(resolvedApp, "package.json")); + let pkgDir: string; + try { + pkgDir = path.dirname(requireFromApp.resolve("tailwindcss/package.json")); + } catch { + log.warn( + colors.yellow( + "⚠️ package.json declares tailwindcss but it is not installed; Tailwind stylesheets will not be compiled", + ), + ); + return undefined; + } + const pkgJson = readJson(path.join(pkgDir, "package.json")); + const major = installedTailwindMajor(pkgJson); + if (major === undefined || major < 4) { + log.warn( + colors.yellow( + `⚠️ installed tailwindcss is v${major ?? "?"}; only v4+ is compiled by the bundler`, + ), + ); + return undefined; + } + log.info(colors.blue("🎨 Tailwind CSS v4 detected, adding tailwind plugin...")); + + const uiDir = sharedUiDir && fs.existsSync(sharedUiDir) ? fs.realpathSync(sharedUiDir) : undefined; + let compilePromise: Promise<TailwindCompile> | undefined; + const moduleMtimes = new Map<string, number | undefined>(); + const loadCompile = () => { + compilePromise ??= (async () => { + const exportsMap = JSON.parse(pkgJson!)?.exports?.["."]; + const entry = typeof exportsMap === "object" && typeof exportsMap.import === "string" + ? path.resolve(pkgDir, exportsMap.import) + : requireFromApp.resolve("tailwindcss"); + const mod = await import(pathToFileURL(entry).href); + const compile = mod.compile ?? mod.default?.compile; + if (typeof compile !== "function") { + throw new Error(`tailwindcss at ${pkgDir} has no compile() export`); + } + return compile as TailwindCompile; + })(); + return compilePromise; + }; + + return { + name: "wmill-tailwind", + setup(build: any) { + const host: TailwindHost = { + loadCompile, + // Through esbuild's own resolver, so `/ui/...`, the "style" export + // condition and bare imports from `ui/` resolve as a plain `@import` would. + async loadStylesheet(id, base) { + const resolved = await build.resolve(id, { + kind: "import-rule", + resolveDir: base, + importer: path.join(base, "__tailwind__.css"), + }); + if (resolved.errors.length > 0) { + throw new Error(resolved.errors[0].text); + } + return { + path: resolved.path, + base: path.dirname(resolved.path), + content: fs.readFileSync(resolved.path, "utf-8"), + }; + }, + rebaseUrl(url, from, to) { + const cut = url.search(/[?#]/); + const file = cut === -1 ? url : url.slice(0, cut); + const suffix = cut === -1 ? "" : url.slice(cut); + const rel = path.relative(to, path.resolve(from, file)).split(path.sep).join("/"); + return (rel.startsWith("../") ? rel : "./" + rel) + suffix; + }, + // `@plugin` / `@config` run in this process, as they would under the + // Tailwind CLI: resolved from the stylesheet, then from the app, and + // imported as is so the module keeps its own location and globals. + // The module cache keeps them for the life of the process, which + // neither Node nor Bun can reset for a whole import graph: in `app dev` + // an edit to one is reported rather than silently built from the old copy. + async loadModule(id, base) { + let resolved: string; + try { + resolved = createRequire(path.join(base, "__tailwind__.js")).resolve(id); + } catch { + resolved = requireFromApp.resolve(id); + } + const mtime = mtimeOf(resolved); + const loadedAt = moduleMtimes.get(resolved); + if (loadedAt === undefined) { + moduleMtimes.set(resolved, mtime); + } else if (loadedAt !== mtime) { + moduleMtimes.set(resolved, mtime); + log.warn( + colors.yellow( + `⚠️ ${path.relative(resolvedApp, resolved)} changed: restart to apply Tailwind \`@config\` / \`@plugin\` changes`, + ), + ); + } + const mod = await import(pathToFileURL(resolved).href); + return { path: resolved, base: path.dirname(resolved), module: mod.default ?? mod }; + }, + async scan(sources: TailwindSource[], includeDefault: boolean) { + const out = { files: new Map<string, string>(), dirs: new Set<string>() }; + if (includeDefault) { + walk(resolvedApp, TAILWIND_SOURCE_EXTENSIONS, new Set([APP_BACKEND_FOLDER]), out, false); + if (uiDir) walk(uiDir, TAILWIND_SOURCE_EXTENSIONS, new Set(), out, false); + } + for (const source of sources) { + const target = path.resolve(source.base, staticPrefix(source.pattern)); + let stat: fs.Stats; + try { + stat = fs.statSync(target); + } catch { + continue; + } + if (stat.isFile()) addFile(target, out); + else walk(target, sourceExtensions(source.pattern), new Set(), out, true); + } + return { + files: [...out.files].map(([p, content]) => ({ path: p, content })), + dirs: [...out.dirs], + }; + }, + }; + + build.onLoad({ filter: /\.css$/, namespace: "file" }, async (args: any) => { + const css = fs.readFileSync(args.path, "utf-8"); + try { + const result = await compileTailwind(css, args.path, path.dirname(args.path), host); + if (!result) return undefined; + return { + contents: result.css, + loader: "css", + resolveDir: path.dirname(args.path), + watchFiles: result.files, + watchDirs: result.dirs, + }; + } catch (e: any) { + return { + errors: [{ text: `Tailwind CSS: ${e?.message ?? e}` }], + watchFiles: [args.path], + }; + } + }); + }, + }; +} diff --git a/cli/src/commands/app/tailwind_core.ts b/cli/src/commands/app/tailwind_core.ts new file mode 100644 index 0000000000..9f8b9b64fd --- /dev/null +++ b/cli/src/commands/app/tailwind_core.ts @@ -0,0 +1,257 @@ +/** + * Tailwind CSS v4 for raw-app builds, independent of the bundler and of where + * files live. The CLI's esbuild and the UI Builder's esbuild-wasm/rolldown + * workers each supply a `TailwindHost`; this file is copied byte for byte into + * windmill-code-ui-builder (`src/lib/tailwind_core.ts`), so keep it free of + * Node and browser APIs and change both copies together. + */ + +/** The `compile` export of the app's own `tailwindcss` (v4). */ +export type TailwindCompile = ( + css: string, + opts: { + base: string; + from?: string; + loadStylesheet: ( + id: string, + base: string, + ) => Promise<{ path: string; base: string; content: string }>; + loadModule: ( + id: string, + base: string, + resourceHint: "plugin" | "config", + ) => Promise<{ path: string; base: string; module: unknown }>; + }, +) => Promise<{ + sources: { base: string; pattern: string; negated: boolean }[]; + root: null | "none" | { base: string; pattern: string }; + features: number; + build(candidates: string[]): string; +}>; + +/** Where `@source` (or `source(...)` on the import) points, before globbing. */ +export interface TailwindSource { + base: string; + pattern: string; +} + +export interface TailwindHost { + /** Loaded on first use, so an app whose stylesheets never need it pays nothing. */ + loadCompile(): Promise<TailwindCompile>; + loadStylesheet( + id: string, + base: string, + ): Promise<{ path: string; base: string; content: string }>; + loadModule( + id: string, + base: string, + resourceHint: "plugin" | "config", + ): Promise<{ path: string; base: string; module: unknown }>; + /** + * `url` as written in a stylesheet in directory `from`, made relative to + * directory `to`, with forward slashes and a leading `./` or `../`. + */ + rebaseUrl(url: string, from: string, to: string): string; + /** + * The files whose class names the stylesheet must cover: the app's sources + * (and the shared `/ui` folder) when `includeDefault`, plus whatever each + * `@source` names. `dirs` are the directories walked, for watch mode. + */ + scan( + sources: TailwindSource[], + includeDefault: boolean, + ): Promise<{ files: { path: string; content: string }[]; dirs: string[] }>; +} + +export interface TailwindResult { + css: string; + /** Every file the output depends on: stylesheets read and sources scanned. */ + files: string[]; + dirs: string[]; +} + +// A stylesheet without any of these is plain CSS and is left to the bundler, +// which is what keeps a Tailwind app's other stylesheets (and every app without +// Tailwind) on the bundler's normal path. +const TAILWIND_DIRECTIVE = + /@(?:import\s+(?:url\(\s*)?["']tailwindcss(?:["'/])|tailwind\b|theme\b|utility\b|apply\b|variant\b|custom-variant\b|source\b|plugin\b|config\b|reference\b)/; + +export function usesTailwind(css: string): boolean { + return TAILWIND_DIRECTIVE.test(css); +} + +/** `"tailwindcss"` at major version 4 or later in a package.json's dependencies. */ +export function declaresTailwindV4(packageJson: string | undefined): boolean { + if (!packageJson) return false; + let pkg: any; + try { + pkg = JSON.parse(packageJson); + } catch { + return false; + } + const spec = pkg?.dependencies?.tailwindcss ?? pkg?.devDependencies?.tailwindcss; + if (typeof spec !== "string") return false; + const major = spec.match(/\d+/); + // A tag or URL ("latest", "next", a git link) has no major to read: latest is v4+. + return major ? Number(major[0]) >= 4 : true; +} + +export function installedTailwindMajor(packageJson: string | undefined): number | undefined { + if (!packageJson) return undefined; + try { + const major = String(JSON.parse(packageJson)?.version ?? "").match(/^\d+/); + return major ? Number(major[0]) : undefined; + } catch { + return undefined; + } +} + +const TRIM_START = /^[\s"'`{}()<>;,=]+/; +const TRIM_END = /[\s"'`{}()<>;,=]+$/; + +function addCandidate(token: string, out: Set<string>) { + let t = token.replace(TRIM_START, "").replace(TRIM_END, ""); + if (t.startsWith("class:")) t = t.slice("class:".length); + if (t.length === 0 || t.length > 300) return; + out.add(t); + // An object key (`clsx({ hidden: open })`, `{hidden:open}`) carries the + // colon, or the value, of the key/value pair it belongs to. + const key = t.match(/^([\w-]+):(?:[A-Za-z_$!][\w$.!]*)?$/); + if (key) out.add(key[1]); +} + +/** `className="after:content-['x']"` -> `className=`, `after:content-['x']`. */ +function splitQuotesOutsideBrackets(token: string): string[] { + const parts: string[] = []; + let depth = 0; + let start = 0; + for (let i = 0; i < token.length; i++) { + const c = token[i]; + if (c === "[") depth++; + else if (c === "]") depth = Math.max(0, depth - 1); + else if (depth === 0 && (c === '"' || c === "'" || c === "`")) { + parts.push(token.slice(start, i)); + start = i + 1; + } + } + parts.push(token.slice(start)); + return parts; +} + +/** + * Every token that might be a class name. Tailwind ignores the ones that are + * not, so this over-collects rather than parse: each whitespace-separated token + * is taken whole, split at quotes outside `[...]`, and split at every quote + * and markup punctuation, which keeps arbitrary values (`data-[state=open]:x`, + * `[&>svg]:size-4`, `className="after:content-['x']"`) intact in at least one cut. + */ +export function extractCandidates(content: string, out: Set<string>): void { + for (const raw of content.split(/\s+/)) { + if (!raw) continue; + addCandidate(raw, out); + for (const part of splitQuotesOutsideBrackets(raw)) addCandidate(part, out); + for (const part of raw.split(/["'`]/)) { + addCandidate(part, out); + for (const sub of part.split(/[{}()<>;,]/)) addCandidate(sub, out); + } + } +} + +/** + * Compiles one stylesheet, or returns undefined when it is not a Tailwind + * stylesheet. `path` is the stylesheet's own path and `base` its directory. + */ +export async function compileTailwind( + css: string, + path: string, + base: string, + host: TailwindHost, +): Promise<TailwindResult | undefined> { + if (!usesTailwind(css)) return undefined; + const compile = await host.loadCompile(); + const files = new Set<string>([path]); + const compiler = await compile(css, { + base, + from: path, + // Tailwind inlines every import into this stylesheet, which the bundler + // then resolves from `base`: a relative url() has to be rebased to keep + // pointing next to the sheet it was written in. + loadStylesheet: async (id, from) => { + const sheet = await host.loadStylesheet(id, from); + files.add(sheet.path); + if (sheet.base === base) return sheet; + return { + ...sheet, + content: rewriteUrls(sheet.content, (url) => host.rebaseUrl(url, sheet.base, base)), + }; + }, + loadModule: async (id, from, hint) => { + const mod = await host.loadModule(id, from, hint); + files.add(mod.path); + return mod; + }, + }); + // Features.None: a directive matched in a comment, say. The bundler's output + // is what the author would get without Tailwind, so hand it back. + if (compiler.features === 0) return undefined; + + const sources: TailwindSource[] = compiler.sources + .filter((s) => !s.negated) + .map((s) => ({ base: s.base, pattern: s.pattern })); + let includeDefault = true; + if (compiler.root === "none") { + includeDefault = false; + } else if (compiler.root) { + includeDefault = false; + sources.push(compiler.root); + } + const scanned = await host.scan(sources, includeDefault); + const candidates = new Set<string>(); + for (const file of scanned.files) { + files.add(file.path); + extractCandidates(file.content, candidates); + } + return { + css: compiler.build([...candidates]), + files: [...files], + dirs: scanned.dirs, + }; +} + +const CSS_URL = /url\(\s*(["']?)([^"')]+?)\1\s*\)/g; +// Absolute, scheme-qualified (data:, https:, …), fragment or variable: not a file path. +const NOT_RELATIVE = /^(?:\/|#|[a-z][a-z0-9+.-]*:|var\()/i; + +/** Applies `rebase` to every relative `url()` in `css`. */ +export function rewriteUrls(css: string, rebase: (url: string) => string): string { + return css.replace(CSS_URL, (match, quote, url) => + NOT_RELATIVE.test(url) ? match : `url(${quote}${rebase(url)}${quote})`, + ); +} + +/** The part of a glob before its first wildcard segment: `src/**\/*.tsx` -> `src`. */ +export function staticPrefix(pattern: string): string { + const segments = pattern.split("/"); + const fixed: string[] = []; + for (const segment of segments) { + if (/[*?{}[\]!]/.test(segment)) break; + fixed.push(segment); + } + return fixed.join("/"); +} + +/** Source file extensions scanned for class names by default. */ +export const TAILWIND_SOURCE_EXTENSIONS = [ + ".tsx", + ".ts", + ".jsx", + ".js", + ".mjs", + ".cjs", + ".mts", + ".cts", + ".svelte", + ".html", + ".md", + ".mdx", +]; diff --git a/cli/src/commands/dependencies/dependencies.ts b/cli/src/commands/dependencies/dependencies.ts index 2daf2d180a..fb2788c80a 100644 --- a/cli/src/commands/dependencies/dependencies.ts +++ b/cli/src/commands/dependencies/dependencies.ts @@ -7,7 +7,13 @@ import * as log from "../../core/log.ts"; import * as wmill from "../../../gen/services.gen.ts"; import fs from "node:fs"; import { workspaceDependenciesPathToLanguageAndFilename } from "../../utils/metadata.ts"; -import { readTextFileSync } from "../../utils/utils.ts"; +import { + apiErrorMessage, + isNoResponseError, + networkErrorMessage, + readTextFileSync, + sleep, +} from "../../utils/utils.ts"; async function push( opts: GlobalOptions, @@ -38,11 +44,52 @@ const command = new Command() .arguments("<file_path:string>") .action(push as any); +export interface WaitOptions { + intervalMs: number; + timeoutMs: number; +} + +const DEFAULT_WAIT: WaitOptions = { intervalMs: 10_000, timeoutMs: 30 * 60_000 }; + +async function waitForWorkspaceDependencies( + workspace: string, + language: Parameters<typeof wmill.getLatestWorkspaceDependencies>[0]["language"], + name: string | undefined, + content: string, + pushError: unknown, + { intervalMs, timeoutMs }: WaitOptions, +): Promise<void> { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + await sleep(intervalMs); + try { + const latest = await wmill.getLatestWorkspaceDependencies({ + workspace, + language, + name, + }); + if (latest?.content === content) { + return; + } + } catch (e) { + log.debug(`Still waiting for workspace dependencies: ${e}`); + } + } + throw new Error( + `The server never applied the pushed ${language} workspace dependencies within ` + + `${Math.round(timeoutMs / 60_000)} min of the request getting no response. ` + + `A server older than this CLI cancels the request when the connection drops: ` + + `retry the push once the server is idle.`, + { cause: pushError }, + ); +} + export async function pushWorkspaceDependencies( workspace: string, path: string, _befObj: any, newDependenciesContent: string, + waitOptions: WaitOptions = DEFAULT_WAIT, ): Promise<void> { const res = workspaceDependenciesPathToLanguageAndFilename(path); if (!res) { @@ -89,17 +136,41 @@ export async function pushWorkspaceDependencies( ), ); - await wmill.createWorkspaceDependencies({ - workspace, - requestBody: { - name, - content: newDependenciesContent, + try { + await wmill.createWorkspaceDependencies({ + workspace, + requestBody: { + name, + content: newDependenciesContent, + language, + workspace_id: workspace, + // Description is not supported in cli, it will use old description + description: undefined, + }, + }); + } catch (e) { + if (!isNoResponseError(e)) { + throw e; + } + // The first default dependencies of a workspace rebuild its whole dependency map before + // the server answers, which can outlast this client's or a proxy's timeout. The server + // finishes regardless, so wait for the pushed content to become the latest version. + log.info( + colors.yellow( + `No response from the server while pushing ${displayName} for ${language} (${ + networkErrorMessage(e) ?? apiErrorMessage(e) + }). Waiting for the server to apply them...`, + ), + ); + await waitForWorkspaceDependencies( + workspace, language, - workspace_id: workspace, - // Description is not supported in cli, it will use old description - description: undefined, - }, - }); + name, + newDependenciesContent, + e, + waitOptions, + ); + } log.info( colors.green(`Successfully pushed ${displayName} for ${language}`), diff --git a/cli/src/commands/flow/flow.ts b/cli/src/commands/flow/flow.ts index 743049933f..94944d3f06 100644 --- a/cli/src/commands/flow/flow.ts +++ b/cli/src/commands/flow/flow.ts @@ -4,6 +4,7 @@ import { Command } from "@cliffy/command"; import { Confirm } from "@cliffy/prompt/confirm"; import { Table } from "@cliffy/table"; import * as log from "../../core/log.ts"; +import { ciTestBatchDeployed, ciTestBatchSkip } from "../../core/ci_test_batch.ts"; import { dirname, sep as SEP, resolve as pathResolve } from "node:path"; import { stringify as yamlStringify } from "yaml"; import { yamlParseFile } from "../../utils/yaml.ts"; @@ -296,6 +297,7 @@ export async function pushFlow( await wmill.updateFlow({ workspace: workspace, path: remotePath.replaceAll(SEP, "/"), + ...ciTestBatchSkip(), requestBody: { path: remotePath.replaceAll(SEP, "/"), deployment_message: message, @@ -306,12 +308,14 @@ export async function pushFlow( skip_draft_deletion: true, }, }); + ciTestBatchDeployed("flow", remotePath.replaceAll(SEP, "/")); } } else { log.info(colors.bold.yellow("Creating new flow...")); try { await wmill.createFlow({ workspace: workspace, + ...ciTestBatchSkip(), requestBody: { path: remotePath.replaceAll(SEP, "/"), deployment_message: message, @@ -328,6 +332,7 @@ export async function pushFlow( `Failed to create flow ${remotePath}: ${e.body ?? e.message}` ); } + ciTestBatchDeployed("flow", remotePath.replaceAll(SEP, "/")); } // Independent of whether the flow body changed, sync extra_perms via /acls/*. diff --git a/cli/src/commands/init/template.ts b/cli/src/commands/init/template.ts index 6b5f220bff..b8f4887681 100644 --- a/cli/src/commands/init/template.ts +++ b/cli/src/commands/init/template.ts @@ -1,3 +1,5 @@ +import { VERSION } from "../../core/constants.ts"; + /** * Configuration option descriptor — each entry IS a JSON Schema property * with extra metadata for template rendering and reference table display. @@ -10,7 +12,8 @@ * Adding a new option: * 1. Add an entry to CONFIG_REFERENCE with JSON Schema type fields + description * 2. Add template rendering hints (section, commented, templateValue, etc.) - * 3. `wmill init` (YAML template), `wmill config` (table), and wmill.schema.json all update automatically + * 3. `wmill init` (YAML template) and `wmill config` (table) update automatically + * 4. Regenerate wmill.schema.json: `bun generate-schema.ts` */ export interface ConfigOption { // --- JSON Schema fields (kept when generating schema) --- @@ -259,10 +262,16 @@ function yamlKey(s: string): string { return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; } +// Absolute and pinned to this CLI's release tag: nothing copies the schema next +// to the user's wmill.yaml (nor into the npm package), and the tag's schema lists +// exactly the options this CLI version accepts. +export const WMILL_SCHEMA_URL = + `https://raw.githubusercontent.com/windmill-labs/windmill/v${VERSION}/cli/wmill.schema.json`; + export function generateCommentedTemplate(branchName?: string, binding?: BranchBinding, bindings?: WorkspaceBinding[]): string { const branch = yamlKey(branchName ?? "main"); const lines: string[] = [ - "# yaml-language-server: $schema=wmill.schema.json", + `# yaml-language-server: $schema=${WMILL_SCHEMA_URL}`, "# wmill.yaml — Windmill CLI configuration", '# Full reference: run "wmill config"', "", diff --git a/cli/src/commands/resource/resource.ts b/cli/src/commands/resource/resource.ts index 87c31b331a..4470daa276 100644 --- a/cli/src/commands/resource/resource.ts +++ b/cli/src/commands/resource/resource.ts @@ -14,6 +14,7 @@ import { Command } from "@cliffy/command"; import { Table } from "@cliffy/table"; import { colors } from "@cliffy/ansi/colors"; import * as log from "../../core/log.ts"; +import { ciTestBatchDeployed, ciTestBatchSkip } from "../../core/ci_test_batch.ts"; import { sep as SEP } from "node:path"; import * as wmill from "../../../gen/services.gen.ts"; import { Resource } from "../../../gen/types.gen.ts"; @@ -151,6 +152,7 @@ export async function pushResource( await wmill.updateResource({ workspace: workspace, path: remotePath.replaceAll(SEP, "/"), + ...ciTestBatchSkip(), requestBody: { ...localResource, ...(wsSpecific !== undefined ? { ws_specific: wsSpecific } : {}), @@ -162,6 +164,7 @@ export async function pushResource( : {}), }, }); + ciTestBatchDeployed("resource", remotePath.replaceAll(SEP, "/")); } else { // New resource - resolve inline content await resolveInlineContent(); @@ -177,12 +180,14 @@ export async function pushResource( log.info(colors.yellow.bold("Creating new resource...")); await wmill.createResource({ workspace: workspace, + ...ciTestBatchSkip(), requestBody: { path: remotePath.replaceAll(SEP, "/"), ...localResource, ...(wsSpecific !== undefined ? { ws_specific: wsSpecific } : {}), }, }); + ciTestBatchDeployed("resource", remotePath.replaceAll(SEP, "/")); } } diff --git a/cli/src/commands/script/script.ts b/cli/src/commands/script/script.ts index 38eec70eeb..28f7ab588c 100644 --- a/cli/src/commands/script/script.ts +++ b/cli/src/commands/script/script.ts @@ -9,6 +9,7 @@ import { import type { PermissionedAsContext } from "../../core/permissioned_as.ts"; import { buildPermissionedAsContext } from "../../core/permissioned_as.ts"; import { applyExtraPermsDiff } from "../../core/extra_perms.ts"; +import { ciTestBatchDeployed, ciTestBatchSkip } from "../../core/ci_test_batch.ts"; import { writeFile, stat, mkdir } from "node:fs/promises"; import { Buffer } from "node:buffer"; import { colors } from "@cliffy/ansi/colors"; @@ -73,7 +74,11 @@ import { createTarBlob, type TarEntry } from "../../utils/tar.ts"; import { withEsbuild } from "../../utils/esbuild_loader.ts"; import { execSync } from "node:child_process"; -import { NewScript, Script, ScriptModule } from "../../../gen/types.gen.ts"; +import { + ListableScript, + NewScript, + ScriptModule, +} from "../../../gen/types.gen.ts"; import { isRawAppBackendPath as isRawAppBackendPathInternal, isAppInlineScriptPath as isAppInlineScriptPathInternal, @@ -1002,7 +1007,9 @@ async function createScript( // skip_if_noop asks the backend to treat deploys identical to the parent // (same content, lockfile, and metadata) as a no-op, so the CLI does not // produce phantom git-sync / promotion commits on re-pushes. - const skipIfNoop = "skip_if_noop=true"; + const skipIfNoop = + "skip_if_noop=true" + + (ciTestBatchSkip().skipCiTests ? "&skip_ci_tests=true" : ""); const extraHeaders = getHeaders(); if (!bundleContent) { try { @@ -1067,6 +1074,7 @@ async function createScript( ); } } + ciTestBatchDeployed("script", body.path); return performance.now() - start; } @@ -1379,7 +1387,7 @@ async function list( let page = 0; const perPage = 10; - const total: Script[] = []; + const total: ListableScript[] = []; while (true) { const res = await wmill.listScripts({ workspace: workspace.workspaceId, @@ -1400,10 +1408,10 @@ async function list( console.log(JSON.stringify(total)); } else { new Table() - .header(["path", "summary", "language", "created by"]) + .header(["path", "summary", "language", "created at"]) .padding(2) .border(true) - .body(total.map((x) => [x.path, x.summary, x.language, x.created_by])) + .body(total.map((x) => [x.path, x.summary, x.language, x.created_at])) .render(); } } diff --git a/cli/src/commands/sync/sync.ts b/cli/src/commands/sync/sync.ts index 01ecce1f29..63521289c8 100644 --- a/cli/src/commands/sync/sync.ts +++ b/cli/src/commands/sync/sync.ts @@ -14,6 +14,12 @@ 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 { + ciTestBatchDeployed, + ciTestBatchSkip, + closeCiTestBatch, + openCiTestBatch, +} from "../../core/ci_test_batch.ts"; import { RETIRED_SETTINGS, SETTINGS_MANAGED_ONLY_WHEN_PRESENT } from "../../core/settings.ts"; import * as path from "node:path"; import { sep as SEP } from "node:path"; @@ -3380,7 +3386,9 @@ export function untrackedDatatableMigrationDeletions< (c) => c.name === "deleted" && isDatatableMigrationPath(c.path) && - !(recorded.kind === "known" && recorded.paths.has(c.path)), + // git reports `/`-separated paths; the sync diff uses the platform's. + !(recorded.kind === "known" && + recorded.paths.has(c.path.replaceAll("\\", "/"))), ); } @@ -5983,6 +5991,7 @@ export async function push( // push. Reported at the end, and the push exits non-zero for them. const failedChanges: { path: string; error: string }[] = []; + openCiTestBatch(); // Create a pool of workers that processes items as they become available const pool = new Set(); // Process folder.meta groups first (sequentially), then items in parallel. @@ -6805,8 +6814,10 @@ export async function push( await wmill.updateResource({ workspace: workspace.workspaceId, path: removeType(target, "resource"), + ...ciTestBatchSkip(), requestBody: { ws_specific: change.wsSpecific }, }); + ciTestBatchDeployed("resource", removeType(target, "resource")); } else if (change.kind === "variable") { await wmill.updateVariable({ workspace: workspace.workspaceId, @@ -6824,15 +6835,25 @@ export async function push( pool.add(promise); // Remove from pool when complete - promise.then(() => { + // Both outcomes: a rejection left unhandled here kills the process before the + // failure path below can close the CI test batch. + const done = () => { pool.delete(promise); if (isFolderGroup) folderPhaseRemaining--; - }); + }; + promise.then(done, done); } // Wait for at least one task to complete before continuing if (pool.size > 0) { - await Promise.race(pool); + try { + await Promise.race(pool); + } catch (e) { + // The items deployed before the failure held their tests back too. + await Promise.allSettled([...pool]); + await closeCiTestBatch(workspace.workspaceId); + throw e; + } } } try { @@ -6860,6 +6881,7 @@ export async function push( pushStartedAt, changes.map((c) => c.path.replaceAll(SEP, "/")), ); + await closeCiTestBatch(workspace.workspaceId); if (!opts.jsonOutput) { for (const f of lockJobs.failed) { log.warn( diff --git a/cli/src/core/ci_test_batch.ts b/cli/src/core/ci_test_batch.ts new file mode 100644 index 0000000000..a495460a79 --- /dev/null +++ b/cli/src/core/ci_test_batch.ts @@ -0,0 +1,74 @@ +import * as wmill from "../../gen/services.gen.ts"; +import * as log from "./log.ts"; + +type CiTestedKind = "script" | "flow" | "resource"; + +// A test run between two deploys of a batch resolves its imports against a +// half-deployed workspace, so while a batch is open every deploy asks the +// server to hold its CI tests back, and the batch queues them once at the end. +// Nothing else queues them: a push that dies before `closeCiTestBatch` leaves +// its batch untested. +let batch: Map<string, { kind: CiTestedKind; path: string }> | undefined; + +export function openCiTestBatch() { + batch = new Map(); +} + +/** The deploy call's `skipCiTests` argument: set only while a batch is open. */ +export function ciTestBatchSkip(): { skipCiTests?: boolean } { + return batch ? { skipCiTests: true } : {}; +} + +/** + * Record a deploy made with `ciTestBatchSkip`, once it has succeeded: the batch + * endpoint refuses an item the caller may not deploy, and with it the batch. + */ +export function ciTestBatchDeployed(kind: CiTestedKind, path: string) { + batch?.set(`${kind}:${path}`, { kind, path }); +} + +const POLL_MS = 2000; +const MAX_WAIT_MS = 10 * 60 * 1000; + +/** + * Queue the CI tests of everything deployed since `openCiTestBatch`, once the + * server reports none of it is still being locked. After `MAX_WAIT_MS` they are + * queued regardless, so a stuck lock job cannot leave the batch untested. + */ +export async function closeCiTestBatch(workspace: string): Promise<string[]> { + const items = [...(batch?.values() ?? [])]; + batch = undefined; + if (items.length === 0) return []; + const deadline = Date.now() + MAX_WAIT_MS; + let announced = false; + try { + while (true) { + const ignorePending = Date.now() >= deadline; + const res = await wmill.triggerCiTestsBatch({ + workspace, + requestBody: { items, ignore_pending: ignorePending }, + }); + if (res.pending.length === 0 || ignorePending) { + if (res.job_ids.length > 0) { + log.info(`Queued ${res.job_ids.length} CI test job(s)`); + } + return res.job_ids; + } + if (!announced) { + const shown = res.pending.slice(0, 5).join(", "); + const more = + res.pending.length > 5 ? ` and ${res.pending.length - 5} more` : ""; + log.info( + `Waiting for lock generation of ${shown}${more} before running CI tests...`, + ); + announced = true; + } + await new Promise((r) => setTimeout(r, POLL_MS)); + } + } catch (e: any) { + // A server that predates this endpoint already ran the tests on each deploy. + if (e?.status === 404) return []; + log.warn(`Failed to queue CI tests: ${e?.body ?? e?.message ?? e}`); + return []; + } +} diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index a431495b12..81218864c7 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.866.0"; +export const VERSION = "1.880.1"; diff --git a/cli/src/core/settings.ts b/cli/src/core/settings.ts index ec796de5d3..ec0035de79 100644 --- a/cli/src/core/settings.ts +++ b/cli/src/core/settings.ts @@ -232,6 +232,20 @@ export async function pushWorkspaceSettings( delete localSettings.datatable_permissions; } + if ( + unreadableSecret(localSettings.webhook) && + !(await documentKeepsRedactedWebhook(workspace)) + ) { + log.warn( + "Leaving the webhook unchanged: this server stores the webhook URL in plain text and cannot read an encrypted or redacted one. Upgrade it, or write the URL in plain text." + ); + const remote = await wmill.getWorkspaceSettingsDocument({ workspace }); + if (typeof remote.webhook === "string") { + localSettings.webhook = remote.webhook; + } else { + delete localSettings.webhook; + } + } if (await applySettingsDocument(workspace, localSettings)) { return; } @@ -240,10 +254,13 @@ export async function pushWorkspaceSettings( 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__"); + const webhookUnreadable = unreadableSecret(localSettings.webhook); + if (webhookUnreadable) { + log.warn( + "Leaving the webhook unchanged: this server cannot read an encrypted or redacted webhook URL. Upgrade it, or write the URL in plain text." + ); + } + const slackSecretUnreadable = unreadableSecret(localSettings.slack_oauth_client_secret); 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." @@ -301,7 +318,7 @@ export async function pushWorkspaceSettings( } log.debug(`Workspace settings are not up-to-date, updating...`); - if (localSettings.webhook !== settings.webhook) { + if (!webhookUnreadable && localSettings.webhook !== settings.webhook) { log.debug(`Updating webhook...`); await wmill.editWebhook({ workspace, @@ -550,6 +567,36 @@ export async function pushWorkspaceSettings( } } +function unreadableSecret(secret: unknown): boolean { + return ( + typeof secret === "string" && + (secret.startsWith("$encrypted:") || secret === "__SENSITIVE_AND_UNCHANGED__") + ); +} + +/** + * Whether the settings document treats the webhook URL as a secret: a server whose document + * predates that plans the placeholder as a new URL, which its webhook endpoint then refuses. + * True for a server without the document, whose fallback path handles the secret itself. + */ +async function documentKeepsRedactedWebhook(workspace: string): Promise<boolean> { + try { + const result = await wmill.applyWorkspaceSettingsDocument({ + workspace, + requestBody: { + document: { webhook: "__SENSITIVE_AND_UNCHANGED__" }, + dry_run: true, + }, + }); + return !result.changes.some((c) => c.key === "webhook"); + } catch (err: any) { + if (err?.status === 404 && !err?.body) { + return true; + } + throw new Error(`Failed to read workspace settings: ${err?.body ?? err}`); + } +} + /** 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( diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index 90da50f8ad..a7acf9f164 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -37,6 +37,8 @@ export const SKILLS: SkillMetadata[] = [ { 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: "code-mode", description: "MUST use when the user asks for something done against the systems the workspace connects to (an API lookup, moving data, checking a status) rather than for building a script, flow or app." }, + { name: "rich-results", description: "MUST use when a script or flow should return a table, chart, markdown, image, file or map instead of plain JSON." }, { 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." }, ]; @@ -811,6 +813,46 @@ async runScriptByHashAsync(hash_: string, args: Record<string, any> | null = nul */ async runFlowAsync(path: string | null, args: Record<string, any> | null, scheduledInSeconds: number | null = null, // can only be set to false if this the job will be fully await and not concurrent with any other job // as otherwise the child flow and its own child will store their state in the parent job which will // lead to incorrectness and failures doNotTrackInParent: boolean = true, tag: string | null = null): Promise<string> +/** + * Run the deployed flow at \`path\` with some of its steps overridden, wait for it and return + * its result. Meant for test scripts. + * + * Each entry of \`steps\` maps a step id to either: + * - a value: the step is skipped and returns that value, or + * - a function exported from the calling script's own file: the step runs that function + * instead of its own code, with the step's inputs as arguments (matched by name). + * + * A step inside a subflow is named by the path of step ids to it, \`"sub:inner"\` for step \`inner\` + * of the subflow that step \`sub\` calls. It applies to every call of that subflow made by the + * tested flow and by the subflows it overrides; a subflow left as is still calls the deployed + * one. Those subflows, and each one on the way to an override, run as you rather than as their + * on-behalf-of identity. Result caching is off for the whole test run. + * + * The flow's preprocessor does not run: \`args\` are what the flow receives after it. A subflow + * never runs its own preprocessor, in a test or not. AI agent + * tools cannot be overridden; override the agent step instead. + * + * @example + * export function fakeFetch(url: string) { return { status: 200 } } + * export async function main() { + * const result = await wmill.testFlow("f/flows/sync", { user: "a" }, { + * fetch_users: fakeFetch, // replaced logic + * send_email: "sent", // mocked result + * }); + * } + * @param path - Flow path in Windmill + * @param args - Arguments to pass to the flow + * @param steps - Step id to mocked result, or to the function replacing the step + * @param verbose - Enable verbose logging + * @returns Flow execution result + */ +async testFlow(path: string, args: Record<string, any> | null = null, steps: Record<string, any> = {}, verbose: boolean = false): Promise<any> + +/** + * Like {@link testFlow}, but returns the job id without waiting for the flow to complete. + */ +async testFlowAsync(path: string, args: Record<string, any> | null = null, steps: Record<string, any> = {}): Promise<string> + /** * Resolve a resource value in case the default value was picked because the input payload was undefined * @param obj resource value or path of the resource under the format \`$res:path\` @@ -1660,6 +1702,46 @@ async runScriptByHashAsync(hash_: string, args: Record<string, any> | null = nul */ async runFlowAsync(path: string | null, args: Record<string, any> | null, scheduledInSeconds: number | null = null, // can only be set to false if this the job will be fully await and not concurrent with any other job // as otherwise the child flow and its own child will store their state in the parent job which will // lead to incorrectness and failures doNotTrackInParent: boolean = true, tag: string | null = null): Promise<string> +/** + * Run the deployed flow at \`path\` with some of its steps overridden, wait for it and return + * its result. Meant for test scripts. + * + * Each entry of \`steps\` maps a step id to either: + * - a value: the step is skipped and returns that value, or + * - a function exported from the calling script's own file: the step runs that function + * instead of its own code, with the step's inputs as arguments (matched by name). + * + * A step inside a subflow is named by the path of step ids to it, \`"sub:inner"\` for step \`inner\` + * of the subflow that step \`sub\` calls. It applies to every call of that subflow made by the + * tested flow and by the subflows it overrides; a subflow left as is still calls the deployed + * one. Those subflows, and each one on the way to an override, run as you rather than as their + * on-behalf-of identity. Result caching is off for the whole test run. + * + * The flow's preprocessor does not run: \`args\` are what the flow receives after it. A subflow + * never runs its own preprocessor, in a test or not. AI agent + * tools cannot be overridden; override the agent step instead. + * + * @example + * export function fakeFetch(url: string) { return { status: 200 } } + * export async function main() { + * const result = await wmill.testFlow("f/flows/sync", { user: "a" }, { + * fetch_users: fakeFetch, // replaced logic + * send_email: "sent", // mocked result + * }); + * } + * @param path - Flow path in Windmill + * @param args - Arguments to pass to the flow + * @param steps - Step id to mocked result, or to the function replacing the step + * @param verbose - Enable verbose logging + * @returns Flow execution result + */ +async testFlow(path: string, args: Record<string, any> | null = null, steps: Record<string, any> = {}, verbose: boolean = false): Promise<any> + +/** + * Like {@link testFlow}, but returns the job id without waiting for the flow to complete. + */ +async testFlowAsync(path: string, args: Record<string, any> | null = null, steps: Record<string, any> = {}): Promise<string> + /** * Resolve a resource value in case the default value was picked because the input payload was undefined * @param obj resource value or path of the resource under the format \`$res:path\` @@ -2618,6 +2700,46 @@ async runScriptByHashAsync(hash_: string, args: Record<string, any> | null = nul */ async runFlowAsync(path: string | null, args: Record<string, any> | null, scheduledInSeconds: number | null = null, // can only be set to false if this the job will be fully await and not concurrent with any other job // as otherwise the child flow and its own child will store their state in the parent job which will // lead to incorrectness and failures doNotTrackInParent: boolean = true, tag: string | null = null): Promise<string> +/** + * Run the deployed flow at \`path\` with some of its steps overridden, wait for it and return + * its result. Meant for test scripts. + * + * Each entry of \`steps\` maps a step id to either: + * - a value: the step is skipped and returns that value, or + * - a function exported from the calling script's own file: the step runs that function + * instead of its own code, with the step's inputs as arguments (matched by name). + * + * A step inside a subflow is named by the path of step ids to it, \`"sub:inner"\` for step \`inner\` + * of the subflow that step \`sub\` calls. It applies to every call of that subflow made by the + * tested flow and by the subflows it overrides; a subflow left as is still calls the deployed + * one. Those subflows, and each one on the way to an override, run as you rather than as their + * on-behalf-of identity. Result caching is off for the whole test run. + * + * The flow's preprocessor does not run: \`args\` are what the flow receives after it. A subflow + * never runs its own preprocessor, in a test or not. AI agent + * tools cannot be overridden; override the agent step instead. + * + * @example + * export function fakeFetch(url: string) { return { status: 200 } } + * export async function main() { + * const result = await wmill.testFlow("f/flows/sync", { user: "a" }, { + * fetch_users: fakeFetch, // replaced logic + * send_email: "sent", // mocked result + * }); + * } + * @param path - Flow path in Windmill + * @param args - Arguments to pass to the flow + * @param steps - Step id to mocked result, or to the function replacing the step + * @param verbose - Enable verbose logging + * @returns Flow execution result + */ +async testFlow(path: string, args: Record<string, any> | null = null, steps: Record<string, any> = {}, verbose: boolean = false): Promise<any> + +/** + * Like {@link testFlow}, but returns the job id without waiting for the flow to complete. + */ +async testFlowAsync(path: string, args: Record<string, any> | null = null, steps: Record<string, any> = {}): Promise<string> + /** * Resolve a resource value in case the default value was picked because the input payload was undefined * @param obj resource value or path of the resource under the format \`$res:path\` @@ -4500,11 +4622,14 @@ def get_client() -> httpx.Client # Args: # endpoint: API endpoint path # raise_for_status: Whether to raise an exception on HTTP errors +# retry_transient: Retry on 429 and 502-504 with exponential backoff, honoring +# Retry-After. Pass False for an endpoint with a side effect. +# retry_budget: Most seconds to spend sleeping between retries (at most 15) # **kwargs: Additional arguments passed to httpx.get # # Returns: # HTTP response object -def get(endpoint, raise_for_status = True, **kwargs) -> httpx.Response +def get(endpoint, raise_for_status = True, *, retry_transient: bool = True, retry_budget: float | None = None, **kwargs) -> httpx.Response # Make an HTTP POST request to the Windmill API. # @@ -4539,6 +4664,16 @@ def run_script_by_hash_async(hash_: str, args: dict = None, scheduled_in_secs: i # Create a flow job and return its job id. def run_flow_async(path: str, args: dict = None, scheduled_in_secs: int = None, do_not_track_in_parent: bool = True, tag: str = None) -> str +# Start the deployed flow at \`\`path\`\` with some steps overridden and return its job id. +# +# See \`\`test_flow\`\` for \`\`steps\`\`. +def test_flow_async(path: str, args: dict = None, steps: dict = None) -> str + +# Run the deployed flow at \`\`path\`\` with some steps overridden and return its result. +# +# See the module-level \`\`test_flow\`\`. +def test_flow(path: str, args: dict = None, steps: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, assert_result_is_not_none: bool = False) -> Any + # Run script by path synchronously and return its result. def run_script_by_path(path: str, args: dict = None, timeout: dt.timedelta | int | float | None = None, verbose: bool = False, cleanup: bool = True, assert_result_is_not_none: bool = False, tag: str = None) -> Any @@ -5917,7 +6052,12 @@ agent or AI decision), \`mcp\` for an MCP server tool, \`websearch\` for web sea built-in \`ask_question\` tool (the agent stops, without holding a worker, until someone answers from the run page or the chat; optional \`value.timeout\` in seconds, default 1800). Set \`requires_approval: true\` on a \`flowmodule\` or \`mcp\` tool to have a person approve or reject each of -its calls before it runs. +its calls before it runs. Set \`background: true\` on a \`flowmodule\` tool that runs long: the agent is +answered as soon as its job starts and keeps working, and gets the result in a later message, +waiting for it without holding a worker if it finishes its answer first. Prefer it to having the +agent start jobs through a script or \`runScriptByPath\`, whose results it cannot wait on. For a tool +that is usually quick but sometimes long, set \`background_after_secs: <seconds>\` instead: the agent +waits that long for the result, then the call continues in the background. \`\`\`json { @@ -6038,7 +6178,7 @@ server's own tool names, so none is name-checked at all — leave those summarie ## AI Decision Modules -An \`aidecision\` module asks a decision model (TypeSafe's Jev, Cloudflare's Clef or OpenAI's Decisions API) typed questions about a \`state\` and +An \`aidecision\` module asks a decision model (TypeSafe's Jev, Cloudflare's Clef, or OpenAI's or Gemini's Decisions API) typed questions about a \`state\` and answers each with calibrated probabilities instead of text. Prefer it over an \`aiagent\` when the step is a judgment (classify, route, score or a yes/no check) that needs no tools and no free text: it is faster, cheaper, and its answers have a fixed shape. @@ -6077,8 +6217,9 @@ is faster, cheaper, and its answers have a fixed shape. \`\`\` - \`provider.kind\` is \`typesafe\` (\`model\` \`jev-latest\` unless a version is pinned), \`cloudflare\` - (\`model\` \`clef\`, or \`clef-flash\` for faster answers) or \`openai\` (\`model\` \`gpt-6-luna\`, never a - chat model); the resource is of that same type + (\`model\` \`clef\`, or \`clef-flash\` for faster answers), \`openai\` (\`model\` \`gpt-6-luna\`, never a + chat model) or \`googleai\` (\`model\` \`gemini-decision-1\`, never a chat model); the resource is of + that same type - \`state\` is the content to evaluate: usually a text, such as the message to classify. To combine several values, pass an object with descriptive keys holding only what the questions need (\`({ message: flow_input.message, plan: results.get_account.plan })\`); an array of strings also works @@ -6098,6 +6239,10 @@ is faster, cheaper, and its answers have a fixed shape. refuses to answer fails the step. A \`state\` that is an array of user messages (\`[{ role: "user", content: [{ type: "input_text", text }, { type: "input_image", image_url: "data:image/png;base64,..." }] }]\`) is sent as is, which is how an image is evaluated; any other object or array is sent as JSON text +- On \`googleai\` the \`questions\` and answers are the same as on \`typesafe\`. If Gemini blocks the + input, the step fails. A \`state\` that is a Gemini content block or an array of them (\`[{ type: "text", text }, { type: "image", mime_type: "image/png", data: "<base64>" }]\`, + where \`image\`, \`audio\`, \`video\` and \`document\` blocks take \`data\` or \`uri\`) is sent as is, which + is how an image or a document is evaluated; any other object or array is sent as JSON text ### Branching on the Answers @@ -6150,6 +6295,7 @@ can call one, not an agent used as a tool. ## Loop Structure Rules - A \`forloopflow\` runs its \`modules\` once per element of \`iterator\`, a javascript expression returning an array (e.g. \`results.get_items\`); \`parallel: true\` runs the iterations concurrently, and \`skip_failures: true\` carries on past a failed iteration +- When iterations are items a user will look for in a run (customers, files, ids), set \`iteration_label\` on the \`forloopflow\` value to a javascript expression naming each one, e.g. \`flow_input.iter.value.name\`; it only labels iterations in the run viewer and never changes what runs - For \`whileloopflow\`, break the loop with a module-level \`stop_after_if\`: on the loop module itself, or on an inner step (required when that step carries state via its own \`results\` — see below) - \`stop_after_if\` is always a sibling of \`id\` and \`value\` on a flow module — never a direct key of the loop's \`value\` object - \`stop_after_all_iters_if\` is for checks after the whole loop finishes, not the normal per-iteration break condition @@ -6466,7 +6612,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-<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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this flow does when its concurrency limit is reached. \`queue\` (default) re-queues it to a later slot, \`fail\` ends it immediately as failed, like any failed step."},"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"},"timeout":{"type":"integer","description":"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error."},"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 after this step completes, before the next step starts (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"},"preview_only":{"type":"boolean","description":"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run."}}},"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this step does when its concurrency limit is reached. \`queue\` (default) re-queues it to a later slot, \`fail\` ends it immediately as failed."},"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"},"max_iterations":{"type":"integer","minimum":1,"description":"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"max_duration_secs":{"type":"integer","minimum":1,"description":"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"}},"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"},"parallelism":{"description":"Maximum number of branches running at once when parallel=true. Can be static number or expression","$ref":"#/components/schemas/InputTransform"}},"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, websearch or question 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."},"requires_approval":{"type":"boolean","description":"Flowmodule and mcp tools only. Each call waits for a person to approve or reject it from the flow's run page or chat, without the agent holding a worker. Calls in the same turn that do not require approval run right away. A rejected call, or one nobody answers within 30 minutes, is reported to the AI as not run."},"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"},{"$ref":"#/components/schemas/QuestionToolValue"}],"discriminator":{"propertyName":"tool_type","mapping":{"flowmodule":"#/components/schemas/FlowModuleTool","mcp":"#/components/schemas/McpToolValue","websearch":"#/components/schemas/WebsearchToolValue","question":"#/components/schemas/QuestionToolValue"}}},"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"]},"QuestionToolValue":{"type":"object","description":"Built-in tool the AI calls as ask_question: the agent stops, releasing its worker, until someone answers from the flow's run page or chat or the question times out, then resumes with the answer as the tool result.","properties":{"tool_type":{"type":"string","enum":["question"]},"timeout":{"type":"integer","description":"Seconds to wait for an answer before the question is reported to the AI as timed out. Defaults to 1800."}},"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":["approval"]},"call_id":{"type":"string"},"calls":{"type":"array","items":{"type":"object","properties":{"function_name":{"type":"string"},"arguments":{}},"required":["function_name","arguments"]}},"expires_at":{"type":"string","format":"date-time"}},"required":["type","call_id","calls","expires_at"]},{"type":"object","properties":{"type":{"type":"string","enum":["question"]},"call_id":{"type":"string"},"question":{"type":"string"},"choices":{"type":"array","items":{"type":"string"},"description":"answers the model proposes; a free-text answer is always possible"},"multi_select":{"type":"boolean","description":"whether several choices can be picked together"},"expires_at":{"type":"string","format":"date-time"}},"required":["type","call_id","question","expires_at"]},{"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this flow does when its concurrency limit is reached. \`queue\` (default) re-queues it to a later slot, \`fail\` ends it immediately as failed, like any failed step."},"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"},"timeout":{"type":"integer","description":"Wall-clock limit in seconds for the whole flow run, counted from its start and including time spent sleeping or suspended at an approval. It also applies when the flow is called as a subflow step, unless that step sets its own timeout, which replaces it. It is checked periodically, so a run can go a few seconds past it. When it expires, the running steps are cancelled, the failure module runs if there is one, and the flow ends cancelled with a timeout error. A calling flow sees the subflow step fail with that error."},"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 after this step completes, before the next step starts (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"},"preview_only":{"type":"boolean","description":"If true, the mock applies only to runs started as a flow preview (from the editor, and every job under it, subflows included). Absent or false, it applies to every run."}}},"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"},"on_concurrency_limit":{"type":"string","enum":["queue","fail"],"description":"What a run of this step does when its concurrency limit is reached. \`queue\` (default) re-queues it to a later slot, \`fail\` ends it immediately as failed."},"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"},"iteration_label":{"description":"Optional expression evaluated once per iteration into the label the run viewers show for it, e.g. 'flow_input.iter.value.name'. It can reference 'flow_input.iter' and 'results'. Purely informational, a failing expression leaves the iteration unlabelled and never fails it. Labels are capped at 100 characters","$ref":"#/components/schemas/InputTransform"}},"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"},"max_iterations":{"type":"integer","minimum":1,"description":"Maximum number of iterations. Checked after each iteration; when reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"},"max_duration_secs":{"type":"integer","minimum":1,"description":"Maximum wall-clock seconds since the first iteration started, checked after each iteration. A running iteration is not interrupted, so the loop can exceed the limit by up to one iteration; the timeout of the body's steps caps an iteration. When reached and stop_after_if did not stop the loop, the loop fails with an error named 'LoopExhausted'"}},"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"},"parallelism":{"description":"Maximum number of branches running at once when parallel=true. Can be static number or expression","$ref":"#/components/schemas/InputTransform"}},"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, websearch or question 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."},"requires_approval":{"type":"boolean","description":"Flowmodule and mcp tools only. Each call waits for a person to approve or reject it from the flow's run page or chat, without the agent holding a worker. Calls in the same turn that do not require approval run right away. A rejected call, or one nobody answers within 30 minutes, is reported to the AI as not run."},"background":{"type":"boolean","description":"Flowmodule tools only. The agent is answered as soon as the tool's job starts and keeps working; the job's result reaches it in a later message. If the agent finishes its answer first, it stops without holding a worker until the job is done, then continues with the result."},"background_after_secs":{"type":"integer","minimum":1,"description":"Flowmodule tools only, with background unset. The agent waits up to this many seconds for the tool's job and gets its result as usual; a job still running then continues as a background one, its result reaching the agent in a later message."},"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"},{"$ref":"#/components/schemas/QuestionToolValue"}],"discriminator":{"propertyName":"tool_type","mapping":{"flowmodule":"#/components/schemas/FlowModuleTool","mcp":"#/components/schemas/McpToolValue","websearch":"#/components/schemas/WebsearchToolValue","question":"#/components/schemas/QuestionToolValue"}}},"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"]},"QuestionToolValue":{"type":"object","description":"Built-in tool the AI calls as ask_question: the agent stops, releasing its worker, until someone answers from the flow's run page or chat or the question times out, then resumes with the answer as the tool result.","properties":{"tool_type":{"type":"string","enum":["question"]},"timeout":{"type":"integer","description":"Seconds to wait for an answer before the question is reported to the AI as timed out. Defaults to 1800."}},"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 or Gemini'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"}}}},"continued_on_error":{"type":"array","description":"On a root flow, the steps at any depth that failed and that the flow went past because of continue_on_error (at most 100).","items":{"type":"object","properties":{"id":{"type":"string"},"job":{"type":"string","format":"uuid"}},"required":["id","job"]}},"test_subflows":{"type":"object","description":"In a flow test run, deployed subflow path -> the flow value with the test's step overrides applied, run in place of the deployed subflow.","additionalProperties":{"type":"object"}}},"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_labels":{"type":"array","description":"For a for-loop step whose iteration_label is set, each iteration's label, aligned with flow_jobs. An entry is null when its label evaluated to nothing","items":{"type":"string","nullable":true}},"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":["approval"]},"call_id":{"type":"string"},"calls":{"type":"array","items":{"type":"object","properties":{"function_name":{"type":"string"},"arguments":{}},"required":["function_name","arguments"]}},"expires_at":{"type":"string","format":"date-time"}},"required":["type","call_id","calls","expires_at"]},{"type":"object","properties":{"type":{"type":"string","enum":["question"]},"call_id":{"type":"string"},"question":{"type":"string"},"choices":{"type":"array","items":{"type":"string"},"description":"answers the model proposes; a free-text answer is always possible"},"multi_select":{"type":"boolean","description":"whether several choices can be picked together"},"expires_at":{"type":"string","format":"date-time"}},"required":["type","call_id","question","expires_at"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","description":"The outcome of each agent action, by position. null while a background tool call is still running.","items":{"type":"boolean","nullable":true}}},"required":["type"]}} `, "raw-app": `--- name: raw-app @@ -6787,6 +6933,10 @@ Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! } **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. +### Styling + +Plain CSS imported from the entrypoint (\`import './index.css'\`) is bundled as is. For **Tailwind CSS v4**, add \`tailwindcss\` (\`^4\`) to \`package.json\` and start \`index.css\` with \`@import "tailwindcss";\`: the bundler then compiles it, generating the utilities used in the app's files and in the workspace's shared \`/ui\` folder, along with \`@theme\`, \`@utility\`, \`@apply\` and \`@custom-variant\`. A design system's stylesheet can live in \`/ui\` and be imported with \`@import "/ui/theme.css";\`. There is no \`tailwind.config.js\`: configure Tailwind in CSS. \`@plugin\` and \`@config\` are compiled only by the CLI (\`wmill app bundle\` / \`wmill app push\`), not by the web editor, and \`wmill app dev\` must be restarted to pick up an edit to one of them or to a file they import. Without the \`tailwindcss\` dependency, Tailwind directives are left uncompiled. + ### Generated bindings (\`wmill.d.ts\` / \`wmill.ts\`) The frontend imports a generated module that mirrors the backend runnables. **Never write to it directly** — it gets regenerated whenever backend runnables change. Modifying it by hand will be overwritten. @@ -8489,7 +8639,8 @@ read or change it. ## Secrets -\`slack_oauth_client_secret\` is the one secret. A read shows \`__SENSITIVE_AND_UNCHANGED__\` in place +\`webhook\` (its URL usually carries the receiver's token) and \`slack_oauth_client_secret\` are the +secrets. 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 @@ -8545,6 +8696,182 @@ instance groups, and the keys \`ducklake\`, \`dbt_warehouses\`, \`deploy_ui\`, \ \`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. +`, + "code-mode": `--- +name: code-mode +description: MUST use when the user asks for something done against the systems the workspace connects to (an API lookup, moving data, checking a status) rather than for building a script, flow or app. +--- + +# Solving a task with code + +When the user asks for something done against the systems their workspace connects to (look +something up in an API, move data, check a status), answer it with a Windmill script run as a +preview: it executes on the workspace's workers, with its resources. A script that worked can be +saved and run as is the next time. + +1. **Look for a saved script first**, by the user's words and by the system the task touches. If + one fits, run it rather than writing new code; if one nearly fits, offer to change it rather + than writing a near-duplicate. +2. **Otherwise write one script and run it as a preview.** Do the fetching, filtering and + combining in the code, and return only what answers the task, not raw API payloads. Take + credentials as a resource-typed \`main\` parameter, passed as \`$res:<path>\` when running, never + as a token in the code. Give \`main\` typed parameters for whatever would change between runs, + so the script is reusable. +3. **Offer to save it** when the task is likely to come back, without saving it unasked. Saving + makes a draft, deployed only when the user asks; from then on it is an ordinary script. + +Load the \`write-script-<language>\` skill before writing the script; the resource's fields are in +\`rt.d.ts\` (\`wmill resource-type generate-namespace\`). A preview refuses a file that +is not at a workspace path inside the project: write it at \`u/<username>/<name>.ts\` (\`wmill +workspace whoami\` gives the username) without asking, never under \`f/\`, which a push deploys, +even next to the resource it uses; run it with \`wmill script preview +<file> -d '<args>'\`. Search with \`wmill script list\` and \`wmill flow list\`; run a deployed one +with \`wmill script run <path>\`. Never push the file on your own. Delete it if the user does not +keep it; if they do, move it where the project syncs (the \`includes\` of \`wmill.yaml\`, \`f/**\` by +default) and push only on their go. +`, + "rich-results": `--- +name: rich-results +description: MUST use when a script or flow should return a table, chart, markdown, image, file or map instead of plain JSON. +--- + +# Rich results + +Windmill renders a script's or flow's return value according to its shape: on run pages, in the +script and flow editors, in app result displays and in AI chat run cards. Anything that matches none +of the shapes below is shown as JSON. + +## Shapes + +- \`{ "table-row-object": [{...}, ...] }\`, or a bare array of objects: a table whose columns are the + union of the objects' keys. +- \`{ "table-col": { "col": [...], ... } }\`, or a bare object of equal-length arrays: a table built + column by column. +- \`{ "table-row": [["col", ...], [v, ...], ...] }\`: a table whose first row holds the column names. +- \`{ "chart": {...} }\`: a bar, line, pie or scatter chart drawn from rows (schema below). A \`chart\` + value the schema rejects is shown as JSON, not as a broken chart. +- \`{ "markdown": "..." }\` (or \`md\`): rendered markdown. +- \`{ "html": "..." }\`: sanitized HTML. +- \`{ "png": "<base64>" }\`, likewise \`jpeg\`, \`gif\`, \`svg\`: an image. \`{ "pdf": "<base64>" }\`: a PDF. +- \`{ "file": "<base64>", "filename": "report.csv" }\`: a download. +- \`{ "map": { "lat": 0, "lon": 0, "zoom": 3, "markers": [{ "lat": 0, "lon": 0, "title": "..." }] } }\`: + a map. +- \`{ "s3": "path/to/key" }\`: an object in the workspace storage, previewed by type. +- \`{ "render_all": [ ... ] }\`: each item rendered in turn with the rules above. + +Each shape is an object with that one key (plus \`filename\` for a file, and an optional \`storage\` for +\`s3\`). A result carrying any other key beside it is shown as JSON. + +## Choosing one + +A chart answers a question at a glance: a trend over time (line), a comparison across categories +(bar), parts of a whole with few parts (pie), or a relation between two numbers (scatter). A table +answers lookups and holds the exact values. When both help, return both in a \`render_all\`: the chart +first, then the table of the same rows. + +Keep a chart to what it shows well: at most 8 series. A pie with more than 8 slices keeps the 7 +largest and folds the rest into "Other", so prefer a bar chart for many categories. Aggregate before +charting: a chart of thousands of raw points says less than one of the totals per day. + +### Chart and table schema + +A chart or table value, as JSON Schema. Beyond it: \`x\` and every \`y\` must be columns of \`data\`, \`y\` columns hold numbers, a scatter chart's \`x\` column holds numbers, and a pie chart takes exactly one \`y\`. + +\`\`\`json +{"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"anyOf":[{"type":"object","properties":{"chart":{"type":"object","properties":{"type":{"description":"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns","type":"string","enum":["bar","line","pie","scatter"]},"title":{"type":"string"},"data":{"description":"The rows to plot, the same shape as a table-row-object result","minItems":1,"maxItems":5000,"type":"array","items":{"description":"One row: column name to value (string, number, boolean or null)","type":"object","propertyNames":{"type":"string"},"additionalProperties":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"}]}}},"x":{"description":"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)","type":"string"},"y":{"description":"Numeric column, or columns, to plot: one series each. A pie takes exactly one","anyOf":[{"type":"string"},{"minItems":1,"maxItems":8,"type":"array","items":{"type":"string"}}]},"stacked":{"description":"bar and line: stack the series","type":"boolean"},"horizontal":{"description":"bar: draw the bars horizontally","type":"boolean"},"x_label":{"type":"string"},"y_label":{"type":"string"}},"required":["type","data","x","y"],"additionalProperties":false}},"required":["chart"],"additionalProperties":false},{"type":"object","properties":{"table-row-object":{"description":"Rows as objects; the columns are the union of their keys","minItems":1,"maxItems":5000,"type":"array","items":{"description":"One row: column name to value (string, number, boolean or null)","type":"object","propertyNames":{"type":"string"},"additionalProperties":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"}]}}}},"required":["table-row-object"],"additionalProperties":false},{"type":"object","properties":{"table-col":{"description":"Columns: column name to its values, all the same length","type":"object","propertyNames":{"type":"string"},"additionalProperties":{"maxItems":5000,"type":"array","items":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"}]}}}},"required":["table-col"],"additionalProperties":false},{"type":"object","properties":{"table-row":{"description":"Rows as arrays; the first row holds the column names","minItems":2,"maxItems":5000,"type":"array","items":{"type":"array","items":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"}]}}}},"required":["table-row"],"additionalProperties":false}]},{"type":"object","properties":{"render_all":{"description":"Several items shown one after another","minItems":1,"maxItems":10,"type":"array","items":{"anyOf":[{"type":"object","properties":{"chart":{"type":"object","properties":{"type":{"description":"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns","type":"string","enum":["bar","line","pie","scatter"]},"title":{"type":"string"},"data":{"description":"The rows to plot, the same shape as a table-row-object result","minItems":1,"maxItems":5000,"type":"array","items":{"description":"One row: column name to value (string, number, boolean or null)","type":"object","propertyNames":{"type":"string"},"additionalProperties":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"}]}}},"x":{"description":"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)","type":"string"},"y":{"description":"Numeric column, or columns, to plot: one series each. A pie takes exactly one","anyOf":[{"type":"string"},{"minItems":1,"maxItems":8,"type":"array","items":{"type":"string"}}]},"stacked":{"description":"bar and line: stack the series","type":"boolean"},"horizontal":{"description":"bar: draw the bars horizontally","type":"boolean"},"x_label":{"type":"string"},"y_label":{"type":"string"}},"required":["type","data","x","y"],"additionalProperties":false}},"required":["chart"],"additionalProperties":false},{"type":"object","properties":{"table-row-object":{"description":"Rows as objects; the columns are the union of their keys","minItems":1,"maxItems":5000,"type":"array","items":{"description":"One row: column name to value (string, number, boolean or null)","type":"object","propertyNames":{"type":"string"},"additionalProperties":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"}]}}}},"required":["table-row-object"],"additionalProperties":false},{"type":"object","properties":{"table-col":{"description":"Columns: column name to its values, all the same length","type":"object","propertyNames":{"type":"string"},"additionalProperties":{"maxItems":5000,"type":"array","items":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"}]}}}},"required":["table-col"],"additionalProperties":false},{"type":"object","properties":{"table-row":{"description":"Rows as arrays; the first row holds the column names","minItems":2,"maxItems":5000,"type":"array","items":{"type":"array","items":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"}]}}}},"required":["table-row"],"additionalProperties":false}]}}},"required":["render_all"],"additionalProperties":false}]} +\`\`\` + +Bar chart, one series per y column: + +\`\`\`json +{ + "chart": { + "type": "bar", + "title": "Runs per day", + "data": [ + { + "day": "2026-11-10", + "success": 42, + "failure": 3 + }, + { + "day": "2026-11-11", + "success": 51, + "failure": 1 + } + ], + "x": "day", + "y": [ + "success", + "failure" + ], + "stacked": true + } +} +\`\`\` + +Pie chart (exactly one y column): + +\`\`\`json +{ + "chart": { + "type": "pie", + "data": [ + { + "language": "python3", + "scripts": 18 + }, + { + "language": "bun", + "scripts": 25 + } + ], + "x": "language", + "y": "scripts" + } +} +\`\`\` + +A chart and a table together: + +\`\`\`json +{ + "render_all": [ + { + "chart": { + "type": "line", + "data": [ + { + "hour": "10:00", + "p95_ms": 120 + }, + { + "hour": "11:00", + "p95_ms": 180 + } + ], + "x": "hour", + "y": "p95_ms", + "y_label": "ms" + } + }, + { + "table-row-object": [ + { + "hour": "10:00", + "p95_ms": 120, + "jobs": 310 + }, + { + "hour": "11:00", + "p95_ms": 180, + "jobs": 402 + } + ] + } + ] +} +\`\`\` `, "cli-commands": `--- name: cli-commands diff --git a/cli/src/main.ts b/cli/src/main.ts index 5cfa102c49..1632d4d7e3 100755 --- a/cli/src/main.ts +++ b/cli/src/main.ts @@ -31,7 +31,11 @@ import review from "./commands/review/review.ts"; import dev from "./commands/dev/dev.ts"; import { GlobalOptions } from "./types.ts"; import { OpenAPI } from "../gen/index.ts"; -import { apiErrorMessage, getHeaders } from "./utils/utils.ts"; +import { + apiErrorMessage, + getHeaders, + networkErrorMessage, +} from "./utils/utils.ts"; import { detectAuthGatewayChallenge } from "./utils/http_guards.ts"; import { setShowDiffs } from "./core/conf.ts"; import { markRequestsAsCliClient } from "./core/client.ts"; @@ -328,8 +332,11 @@ async function main() { await command.parse(args); } catch (e) { const apiError = apiErrorMessage(e); + const networkError = networkErrorMessage(e); if (apiError !== undefined) { log.error("Server failed. " + apiError); + } else if (networkError !== undefined) { + log.error(networkError); } else if (e instanceof Error) { log.error(e.message); } else if (e !== undefined && e !== null) { diff --git a/cli/src/types.ts b/cli/src/types.ts index 3ae2b8d6a4..3863a10ad3 100644 --- a/cli/src/types.ts +++ b/cli/src/types.ts @@ -328,7 +328,8 @@ export function parseFromFile(p: string): any { export function parseDatatableMigrationPath(p: string): | { datatable: string; timestamp: number; name: string; kind: "up" | "down" } | undefined { - const parts = p.split("/"); + // Local paths carry the platform separator (`\` on Windows). + const parts = p.split(/[\\/]/); if ( parts[0] !== "migrations" || parts[1] !== "datatable" || diff --git a/cli/src/utils/utils.ts b/cli/src/utils/utils.ts index 526dffbde4..9bc2751d11 100644 --- a/cli/src/utils/utils.ts +++ b/cli/src/utils/utils.ts @@ -371,6 +371,77 @@ export function apiErrorMessage(e: unknown): string | undefined { return statusText + ": " + bodyStr.replace(/\s*[@(]\w+\.rs:\d+[:\d]*\)?/g, ""); } +function fetchFailureCause( + e: unknown, +): { code?: string; message?: string } | undefined { + if (!(e instanceof TypeError)) { + return undefined; + } + if (e.message === "fetch failed") { + const cause = (e as { cause?: unknown }).cause; + return cause && typeof cause === "object" + ? (cause as { code?: string; message?: string }) + : {}; + } + // Bun puts the code on the error itself. Node's own argument errors carry an `ERR_` code + // too, and are not network failures. + const code = (e as { code?: unknown }).code; + return typeof code === "string" && !code.startsWith("ERR_") + ? { code, message: e.message } + : undefined; +} + +/** + * A readable message for a request that got no response from the server, which Node reports + * as a bare "fetch failed" with the actual reason in `cause`. Undefined for anything else. + */ +export function networkErrorMessage(e: unknown): string | undefined { + const cause = fetchFailureCause(e); + if (!cause) { + return undefined; + } + const detail = [cause.message, cause.code && `(${cause.code})`] + .filter(Boolean) + .join(" "); + if (cause.code === "UND_ERR_HEADERS_TIMEOUT") { + return ( + `The Windmill server did not respond in time: ${detail}. ` + + `It may still be processing the request.` + ); + } + if (cause.code !== undefined && NO_RESPONSE_CODES.has(cause.code)) { + return ( + `The connection to the Windmill server closed before it responded: ${detail}. ` + + `It may still be processing the request.` + ); + } + return `Could not reach the Windmill server: ${detail || "fetch failed"}`; +} + +const NO_RESPONSE_CODES = new Set([ + "UND_ERR_HEADERS_TIMEOUT", + "UND_ERR_BODY_TIMEOUT", + "UND_ERR_SOCKET", + "ECONNRESET", +]); + +/** + * True when a request was sent but its outcome is unknown: the client timed out, the + * connection dropped mid-request, or a proxy in front of the server gave up (502/504). + * The server may still complete the request. + */ +export function isNoResponseError(e: unknown): boolean { + const cause = fetchFailureCause(e); + if (cause) { + return cause.code !== undefined && NO_RESPONSE_CODES.has(cause.code); + } + if (e && typeof e === "object" && "name" in e && e.name === "ApiError") { + const status = (e as { status?: number }).status; + return status === 502 || status === 504; + } + return false; +} + /** * Validate that required arguments are present when no -d data was provided. * Fetches the schema from the API and checks required fields. diff --git a/cli/test/datatable_migrations_unit.test.ts b/cli/test/datatable_migrations_unit.test.ts index 2db9371629..431b5792fa 100644 --- a/cli/test/datatable_migrations_unit.test.ts +++ b/cli/test/datatable_migrations_unit.test.ts @@ -36,6 +36,12 @@ describe("parseDatatableMigrationPath", () => { ).toEqual({ datatable: "my-dt", timestamp: 42, name: "x", kind: "down" }); }); + test("parses Windows-separated paths", () => { + expect( + parseDatatableMigrationPath("migrations\\datatable\\mydt\\1_x.up.sql"), + ).toEqual({ datatable: "mydt", timestamp: 1, name: "x", kind: "up" }); + }); + test("rejects unrelated, legacy and malformed paths", () => { for ( const p of [ @@ -149,6 +155,13 @@ describe("untrackedDatatableMigrationDeletions", () => { ).toEqual([]); }); + test("matches Windows-separated diff paths against git's paths", () => { + const win = changes.map((c) => ({ ...c, path: c.path.replaceAll("/", "\\") })); + expect( + untrackedDatatableMigrationDeletions(win, { kind: "known", paths: new Set([A_UP, A_DOWN]) }), + ).toEqual([]); + }); + test("flags migrations this repository has never recorded", () => { expect( untrackedDatatableMigrationDeletions(changes, { kind: "known", paths: new Set() }).map((c) => c.path), diff --git a/cli/test/deploy_labels_unit.test.ts b/cli/test/deploy_labels_unit.test.ts index 2686eb8cc6..f630500a62 100644 --- a/cli/test/deploy_labels_unit.test.ts +++ b/cli/test/deploy_labels_unit.test.ts @@ -19,6 +19,7 @@ test("deployItem: carries labels for variables, resources and folders", async () }), getFolder: async () => ({ name: "x", + display_name: "X folder", owners: [], extra_perms: {}, labels, @@ -64,6 +65,44 @@ test("deployItem: carries labels for variables, resources and folders", async () "updateVariable", ]); for (const [, body] of writes) expect(body.labels).toEqual(labels); + // The compare page flags a folder whose display name differs, so dropping it leaves a + // conflict no deploy can clear. + for (const [fn, body] of writes) { + if (fn.endsWith("Folder")) expect(body.display_name).toEqual("X folder"); + if (fn.endsWith("Resource")) expect(body.resource_type).toEqual("postgresql"); + } +}); + +test("deployItem: carries a resource type's file settings and clears unset ones", async () => { + const bodies: Record<string, any> = {}; + const deploy = (exists: boolean, rt: any) => + deployItem( + { + existsResourceType: async () => exists, + getResourceType: async () => rt, + createResourceType: async (p: any) => void (bodies.create = p.requestBody), + updateResourceType: async (p: any) => void (bodies.update = p.requestBody), + } as any, + "resource_type", + "csv_file", + "src", + "dst", + ); + for (const rt of [ + { name: "csv_file", schema: {}, format_extension: "csv" }, + { name: "csv_file", schema: {}, is_fileset: true }, + ]) { + await deploy(false, rt); + await deploy(true, rt); + for (const body of [bodies.create, bodies.update]) { + expect(body.format_extension ?? undefined).toEqual(rt.format_extension); + expect(body.is_fileset ?? false).toEqual(rt.is_fileset ?? false); + } + } + // A type that stopped being a file type reads back without the fields. + await deploy(true, { name: "csv_file", schema: {} }); + expect(bodies.update.format_extension).toBeNull(); + expect(bodies.update.is_fileset).toEqual(false); }); test("deployItem: clears a folder's labels when the source has none", async () => { diff --git a/cli/test/init_template_unit.test.ts b/cli/test/init_template_unit.test.ts index 7070de63c8..391d31d7fe 100644 --- a/cli/test/init_template_unit.test.ts +++ b/cli/test/init_template_unit.test.ts @@ -3,8 +3,11 @@ */ import { expect, test, describe } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import { parse } from "yaml"; import Ajv from "ajv"; +import { VERSION } from "../src/core/constants.ts"; import { generateCommentedTemplate, generateJsonSchema, @@ -65,9 +68,13 @@ describe("generateCommentedTemplate", () => { expect(config.workspaces["prod"].workspaceId).toBe("prod-ws"); }); - test("contains yaml-language-server schema directive", () => { + // The header must be an absolute URL: a relative path resolves next to the + // user's wmill.yaml, where no schema file exists. + test("first line points the YAML language server at the schema of this CLI's release tag", () => { const yaml = generateCommentedTemplate("main"); - expect(yaml.startsWith("# yaml-language-server: $schema=wmill.schema.json")).toBe(true); + expect(yaml.split("\n")[0]).toBe( + `# yaml-language-server: $schema=https://raw.githubusercontent.com/windmill-labs/windmill/v${VERSION}/cli/wmill.schema.json`, + ); }); test("includes all non-commented, non-skipped CONFIG_REFERENCE entries as active YAML keys", () => { @@ -105,6 +112,14 @@ describe("generateCommentedTemplate", () => { describe("generateJsonSchema", () => { const schema = generateJsonSchema(); + // wmill.yaml headers fetch cli/wmill.schema.json from the release tag, so the + // committed file is what users validate against. Regenerate: `bun generate-schema.ts`. + test("matches the committed cli/wmill.schema.json", () => { + const committed = readFileSync(join(import.meta.dir, "..", "wmill.schema.json"), "utf-8") + .replace(/\r\n/g, "\n"); + expect(committed).toBe(JSON.stringify(schema, null, 2) + "\n"); + }); + test("is a valid JSON Schema draft-07", () => { expect(schema.$schema).toBe("http://json-schema.org/draft-07/schema#"); expect(schema.type).toBe("object"); diff --git a/cli/test/raw_app_tailwind_unit.test.ts b/cli/test/raw_app_tailwind_unit.test.ts new file mode 100644 index 0000000000..b2afb693cd --- /dev/null +++ b/cli/test/raw_app_tailwind_unit.test.ts @@ -0,0 +1,106 @@ +/** + * Tailwind CSS v4 in `createBundle`: compiled only when the app declares + * `tailwindcss`, from the app's own install, scanning the shared `ui/` folder. + */ + +import { afterAll, beforeAll, expect, test } from "bun:test"; +import * as fs from "node:fs"; +import * as path from "node:path"; +import * as os from "node:os"; +import { createBundle } from "../src/commands/app/bundle.ts"; + +let root: string; +const originalCwd = process.cwd(); +const cliNodeModules = path.resolve(import.meta.dir, "../node_modules"); + +function app(name: string, dependencies: Record<string, string>) { + const dir = path.join(root, name); + const write = (rel: string, content: string) => { + fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true }); + fs.writeFileSync(path.join(dir, rel), content); + }; + write("package.json", JSON.stringify({ dependencies })); + write("index.css", `@import "tailwindcss";\n@import "/ui/theme.css";\n@source "../lib";\n`); + write( + "index.ts", + `import "./index.css";\nimport { card } from "/ui/card";\nconsole.log(card, "flex data-[state=open]:p-3");\n` + + "console.log(`<div className=\"after:content-['hello']\"></div><div class=\"bg-[url('https://x.test/hero.png')]\"></div>`);\n" + + "const open = true;\nconsole.log({ hidden: open, grid: !open }, {italic:open});\n", + ); + // The app's own install, as `bun install` would leave it. + fs.symlinkSync(cliNodeModules, path.join(dir, "node_modules")); + return dir; +} + +beforeAll(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), "raw-app-tailwind-")); + fs.mkdirSync(path.join(root, "ui")); + fs.writeFileSync( + path.join(root, "ui/theme.css"), + `@theme { --color-brand: #123456; }\n@utility glow { box-shadow: 0 0 2px red; }\n`, + ); + fs.writeFileSync(path.join(root, "ui/card.ts"), `export const card = "bg-brand glow";\n`); + // A component library built to dist/, scanned through an explicit @source. + fs.mkdirSync(path.join(root, "lib/dist"), { recursive: true }); + fs.writeFileSync(path.join(root, "lib/dist/button.js"), `export const button = "tracking-widest";\n`); +}); + +afterAll(() => { + process.chdir(originalCwd); + fs.rmSync(root, { recursive: true, force: true }); +}); + +async function bundle(dir: string) { + process.chdir(dir); + return createBundle({ + entryPoint: path.join(dir, "index.ts"), + minify: false, + sharedUiDir: path.join(root, "ui"), + }); +} + +test("an app declaring tailwindcss gets the utilities it and ui/ use", async () => { + const { css } = await bundle(app("with", { tailwindcss: "^4.1.0" })); + expect(css).not.toContain("@tailwind"); + for (const selector of [ + ".hidden", + ".grid", + ".italic", + ".tracking-widest", + ".bg-brand", + "#123456", + ".glow", + ".flex", + "data-\\[state\\=open\\]\\:p-3", + "after\\:content-\\[\\'hello\\'\\]", + "https://x.test/hero.png", + ]) { + expect(css).toContain(selector); + } +}); + +test("an app without the dependency builds as before", async () => { + const { css } = await bundle(app("without", {})); + expect(css).toContain("@tailwind utilities"); + expect(css).not.toContain(".bg-brand"); +}); + +// A config is the app's own Node module: it must run from where it lives. +test("an @config runs with its own __dirname and imports", async () => { + const dir = path.join(root, "config"); + fs.mkdirSync(dir); + fs.symlinkSync(cliNodeModules, path.join(dir, "node_modules")); + fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify({ dependencies: { tailwindcss: "^4.1.0" } })); + fs.writeFileSync(path.join(dir, "index.css"), `@import "tailwindcss";\n@config "./tw.config.cjs";\n`); + fs.writeFileSync(path.join(dir, "index.ts"), `import "./index.css";\nconsole.log("text-brand");\n`); + fs.writeFileSync(path.join(dir, "tokens.json"), JSON.stringify({ brand: "#123456" })); + fs.writeFileSync( + path.join(dir, "tw.config.cjs"), + `const path = require("node:path");\n` + + `const { brand } = require(path.join(__dirname, "tokens.json"));\n` + + `module.exports = { theme: { extend: { colors: { brand } } } };\n`, + ); + process.chdir(dir); + const { css } = await createBundle({ entryPoint: path.join(dir, "index.ts"), minify: false }); + expect(css).toContain("#123456"); +}); diff --git a/cli/test/workspace_dependencies_push_wait_unit.test.ts b/cli/test/workspace_dependencies_push_wait_unit.test.ts new file mode 100644 index 0000000000..c6001a9bfb --- /dev/null +++ b/cli/test/workspace_dependencies_push_wait_unit.test.ts @@ -0,0 +1,86 @@ +// A workspace dependencies push whose request gets no response (the server can take longer +// than the client's or a proxy's timeout to rebuild the dependency map) waits for the pushed +// content to land instead of failing the sync. + +import { afterEach, expect, test } from "bun:test"; +import { OpenAPI } from "../gen/index.ts"; +import { pushWorkspaceDependencies } from "../src/commands/dependencies/dependencies.ts"; +import { + isNoResponseError, + networkErrorMessage, +} from "../src/utils/utils.ts"; + +const PUSHED = "requests==2.32.0\n"; +const FAST = { intervalMs: 10, timeoutMs: 2_000 }; + +let server: ReturnType<typeof Bun.serve> | undefined; +afterEach(() => server?.stop(true)); + +function stubServer(appliedAfterPolls: number | null) { + let polls = 0; + server = Bun.serve({ + port: 0, + fetch(req) { + const url = new URL(req.url); + if (url.pathname.endsWith("/workspace_dependencies/create")) { + return new Response("Gateway Timeout", { status: 504 }); + } + if (url.pathname.includes("/workspace_dependencies/get_latest/")) { + // The first read is the up-to-date check that precedes the push. + const applied = appliedAfterPolls !== null && polls++ > appliedAfterPolls; + return Response.json({ content: applied ? PUSHED : "requests==2.31.0\n" }); + } + return new Response("not found", { status: 404 }); + }, + }); + OpenAPI.BASE = `http://localhost:${server.port}/api`; + return () => polls; +} + +test("a push that times out at a proxy succeeds once the server applies it", async () => { + const polls = stubServer(2); + await pushWorkspaceDependencies("ws", "dependencies/requirements.in", null, PUSHED, FAST); + expect(polls()).toBeGreaterThan(2); +}); + +test("a push the server never applies fails with the push error as its cause", async () => { + stubServer(null); + const err = await pushWorkspaceDependencies( + "ws", + "dependencies/requirements.in", + null, + PUSHED, + { intervalMs: 10, timeoutMs: 100 }, + ).catch((e) => e); + expect(err).toBeInstanceOf(Error); + expect(err.message).toContain("never applied"); + expect(err.cause?.status).toBe(504); +}); + +test("Node's bare fetch failure is reported with its cause", () => { + const headersTimeout = new TypeError("fetch failed", { + cause: Object.assign(new Error("Headers Timeout Error"), { + code: "UND_ERR_HEADERS_TIMEOUT", + }), + }); + expect(isNoResponseError(headersTimeout)).toBe(true); + expect(networkErrorMessage(headersTimeout)).toContain( + "did not respond in time: Headers Timeout Error (UND_ERR_HEADERS_TIMEOUT)", + ); + + const refused = new TypeError("fetch failed", { + cause: Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:8000"), { + code: "ECONNREFUSED", + }), + }); + // Nothing reached the server, so there is nothing to wait for. + expect(isNoResponseError(refused)).toBe(false); + + const invalidUrl = Object.assign(new TypeError("Invalid URL"), { + code: "ERR_INVALID_URL", + }); + expect(networkErrorMessage(invalidUrl)).toBeUndefined(); + expect(networkErrorMessage(refused)).toBe( + "Could not reach the Windmill server: connect ECONNREFUSED 127.0.0.1:8000 (ECONNREFUSED)", + ); +}); diff --git a/cli/windmill-utils-internal/package-lock.json b/cli/windmill-utils-internal/package-lock.json index 3babfd3631..f28668938c 100644 --- a/cli/windmill-utils-internal/package-lock.json +++ b/cli/windmill-utils-internal/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-utils-internal", - "version": "1.8.4", + "version": "1.8.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-utils-internal", - "version": "1.8.4", + "version": "1.8.6", "license": "Apache 2.0", "devDependencies": { "@types/node": "^24.2.0", diff --git a/cli/windmill-utils-internal/package.json b/cli/windmill-utils-internal/package.json index 4b3c96903d..2b80f84f81 100644 --- a/cli/windmill-utils-internal/package.json +++ b/cli/windmill-utils-internal/package.json @@ -1,6 +1,6 @@ { "name": "windmill-utils-internal", - "version": "1.8.4", + "version": "1.8.6", "description": "Internal utility functions for Windmill", "main": "dist/cjs/index.js", "module": "dist/esm/index.js", @@ -36,4 +36,4 @@ "files": [ "dist/**/*" ] -} \ No newline at end of file +} diff --git a/cli/windmill-utils-internal/src/deploy.ts b/cli/windmill-utils-internal/src/deploy.ts index 77d093f74f..babb2f8a90 100644 --- a/cli/windmill-utils-internal/src/deploy.ts +++ b/cli/windmill-utils-internal/src/deploy.ts @@ -665,6 +665,7 @@ export async function deployItem( requestBody: { path, value, + resource_type: resource.resource_type, description: resource.description ?? "", labels: resource.labels, ...agentPreserve, @@ -695,6 +696,11 @@ export async function deployItem( requestBody: { schema: rt.schema, description: rt.description ?? "", + is_fileset: rt.is_fileset ?? false, + // An omitted extension or name is left unchanged, so an unset one is sent as null + // to clear what the target has. + format_extension: rt.format_extension ?? null, + display_name: rt.display_name ?? null, }, }); } else { @@ -704,6 +710,9 @@ export async function deployItem( name: rt.name, schema: rt.schema, description: rt.description ?? "", + is_fileset: rt.is_fileset, + format_extension: rt.format_extension, + display_name: rt.display_name, }, }); } @@ -718,6 +727,7 @@ export async function deployItem( workspace: workspaceTo, name, requestBody: { + display_name: folder.display_name, owners: folder.owners, extra_perms: folder.extra_perms, summary: folder.summary ?? undefined, @@ -731,6 +741,7 @@ export async function deployItem( workspace: workspaceTo, requestBody: { name, + display_name: folder.display_name, owners: folder.owners, extra_perms: folder.extra_perms, summary: folder.summary ?? undefined, @@ -916,6 +927,7 @@ export async function getItemValue( return { summary: flow.summary, description: flow.description, + schema: flow.schema, value: flow.value, job_token_scopes: flow.job_token_scopes ?? null, }; @@ -926,6 +938,7 @@ export async function getItemValue( lock: script.lock, schema: script.schema, summary: script.summary, + description: script.description, language: script.language, job_token_scopes: script.job_token_scopes ?? null, }; @@ -945,15 +958,25 @@ export async function getItemValue( }; } else if (kind === "resource") { const resource = await provider.getResource({ workspace, path }); + let value = resource.value; // 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; + if (resource.resource_type === "ai_agent" && value) { + const { on_behalf_of: _, ...rest } = value; + value = rest; } - return resource.value; + return { + value, + description: resource.description, + resource_type: resource.resource_type, + }; } else if (kind === "resource_type") { const rt = await provider.getResourceType({ workspace, path }); - return rt.schema; + return { + schema: rt.schema, + description: rt.description, + format_extension: rt.format_extension, + is_fileset: rt.is_fileset, + }; } else if (kind === "folder") { const folder = await provider.getFolder({ workspace, @@ -961,6 +984,7 @@ export async function getItemValue( }); return { name: folder.name, + display_name: folder.display_name, owners: folder.owners, extra_perms: folder.extra_perms, summary: folder.summary, diff --git a/cli/wmill.schema.json b/cli/wmill.schema.json index 15af745438..2b9c047c42 100644 --- a/cli/wmill.schema.json +++ b/cli/wmill.schema.json @@ -93,6 +93,10 @@ "type": "boolean", "description": "Include workspace settings in sync" }, + "includeDatatablePermissions": { + "type": "boolean", + "description": "With includeSettings, also sync each data table's roles and who may connect as them" + }, "includeKey": { "type": "boolean", "description": "Include encryption key in sync" diff --git a/debugger/Dockerfile b/debugger/Dockerfile index be30570425..0b1d208aad 100644 --- a/debugger/Dockerfile +++ b/debugger/Dockerfile @@ -19,7 +19,7 @@ FROM ghcr.io/windmill-labs/windmill-ee:main AS windmill-source # Stage 2: Build the debug service -FROM oven/bun:1.4.4 AS runtime +FROM oven/bun:1.4.5 AS runtime # Install Python and required system dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ diff --git a/docker/DockerfileExtra b/docker/DockerfileExtra index 7eb2de6bf7..3ea90a8e69 100644 --- a/docker/DockerfileExtra +++ b/docker/DockerfileExtra @@ -19,7 +19,10 @@ # ============================================================================ # Build final extra services image from windmill-ee-slim (includes nsjail) # ============================================================================ -FROM ghcr.io/windmill-labs/windmill-ee-slim:latest AS final +# Release builds pass this release's ee-slim by digest: at tag time :latest is +# still the previous release. +ARG BASE_IMAGE=ghcr.io/windmill-labs/windmill-ee-slim:latest +FROM ${BASE_IMAGE} AS final ARG APP=/usr/src/app @@ -44,9 +47,9 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ RUN set -eux; \ arch="$(dpkg --print-architecture)"; arch="${arch##*-}"; \ case "$arch" in \ - 'amd64') targz='go1.27.3.linux-amd64.tar.gz' ;; \ - 'arm64') targz='go1.27.3.linux-arm64.tar.gz' ;; \ - 'armhf') targz='go1.27.3.linux-armv6l.tar.gz' ;; \ + 'amd64') targz='go1.27.4.linux-amd64.tar.gz' ;; \ + 'arm64') targz='go1.27.4.linux-arm64.tar.gz' ;; \ + 'armhf') targz='go1.27.4.linux-armv6l.tar.gz' ;; \ *) echo >&2 "error: unsupported architecture '$arch'"; exit 1 ;; \ esac; \ wget "https://golang.org/dl/$targz" -nv && tar -C /usr/local -xzf "$targz" && rm "$targz" @@ -138,9 +141,16 @@ RUN addgroup --gid 1000 windmill && \ # (/tmp/windmill/cache/uv) after the base already made it world-writable, leaving # root-owned 0755 dirs that make uv fail EACCES for a non-root UID. /pyls/.cache # (XDG_CACHE_HOME, incl. DENO_DIR) and /tmp/monaco are written at runtime too. -RUN chmod -R a+rX /usr/local /pyls /debugger /multiplayer /tmp/monaco && \ - chmod -R a+rw /tmp/windmill /pyls/.cache && \ - find /tmp/windmill /pyls/.cache /tmp/monaco -type d -exec chmod 777 {} + +# Each find touches only paths missing the bits (same result as chmod -R): a +# chmod on a file from an earlier layer copies it into this layer, so a blanket +# chmod -R costs 15 min and 330 MB per arch here. +RUN find /usr/local /pyls /debugger /multiplayer /tmp/monaco ! -type l \ + \( ! -perm -a+r -o -perm /111 ! -perm -a+x -o -type d ! -perm -a+x \) \ + -exec chmod a+rX {} + && \ + find /tmp/windmill /pyls/.cache ! -type d ! -type l ! -perm -a+rw \ + -exec chmod a+rw {} + && \ + find /tmp/windmill /pyls/.cache /tmp/monaco -type d ! -perm 777 \ + -exec chmod 777 {} + # Expose all service ports EXPOSE 3000 3001 3002 3003 diff --git a/docker/DockerfileFull b/docker/DockerfileFull index d145a5ffff..e1299de610 100644 --- a/docker/DockerfileFull +++ b/docker/DockerfileFull @@ -70,5 +70,7 @@ RUN apt-get install -y r-base-dev \ # Fix UV cache permissions for non-root user support (uid 1000, etc.) # The uv tool install ansible command populates the UV cache with root-owned files -RUN chmod -R a+rw /tmp/windmill/cache/uv && \ - find /tmp/windmill/cache/uv -type d -exec chmod 777 {} + +# Only paths missing the bits are touched: a chmod on a file from an earlier layer +# copies it into this layer, so a blanket chmod -R costs minutes per arch. +RUN find /tmp/windmill/cache/uv \( -type d ! -perm 777 -exec chmod 777 {} + \) \ + -o \( ! -type d ! -type l ! -perm -a+rw -exec chmod a+rw {} + \) diff --git a/docker/DockerfileFullEe b/docker/DockerfileFullEe index 8ca1067f7a..3b9817d96d 100644 --- a/docker/DockerfileFullEe +++ b/docker/DockerfileFullEe @@ -104,5 +104,7 @@ RUN apt-get install -y libsasl2-modules-gssapi-mit krb5-user # Fix UV cache permissions for non-root user support (uid 1000, etc.) # The uv tool install ansible command populates the UV cache with root-owned files -RUN chmod -R a+rw /tmp/windmill/cache/uv && \ - find /tmp/windmill/cache/uv -type d -exec chmod 777 {} + +# Only paths missing the bits are touched: a chmod on a file from an earlier layer +# copies it into this layer, so a blanket chmod -R costs minutes per arch. +RUN find /tmp/windmill/cache/uv \( -type d ! -perm 777 -exec chmod 777 {} + \) \ + -o \( ! -type d ! -type l ! -perm -a+rw -exec chmod a+rw {} + \) diff --git a/docker/DockerfileSlim b/docker/DockerfileSlim index 479d181c19..1969387d8c 100644 --- a/docker/DockerfileSlim +++ b/docker/DockerfileSlim @@ -47,7 +47,7 @@ ENV PATH=/usr/local/bin:/root/.local/bin:/tmp/.local/bin:$PATH # Install system dependencies # Bump to force a fresh apt-get upgrade past the build cache; keep in step with ../Dockerfile. -ARG APT_REFRESH=1 +ARG APT_REFRESH=2 RUN echo "apt refresh ${APT_REFRESH}" \ && apt-get update \ && apt-get upgrade -y \ @@ -66,7 +66,7 @@ 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.13.6/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.8/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 @@ -82,7 +82,7 @@ RUN mkdir -p /tmp/windmill/cache && \ rm -rf /tmp/build_cache && \ mkdir -p -m 777 /tmp/windmill/cache/uv -COPY --from=oven/bun:1.4.4 /usr/local/bin/bun /usr/bin/bun +COPY --from=oven/bun:1.4.5 /usr/local/bin/bun /usr/bin/bun # Install windmill CLI (node symlink needed for bun install) RUN ln -s /usr/bin/bun /usr/bin/node \ diff --git a/docker/DockerfileSlimEe b/docker/DockerfileSlimEe index c1f9a8af7c..ef7ac72991 100644 --- a/docker/DockerfileSlimEe +++ b/docker/DockerfileSlimEe @@ -47,7 +47,7 @@ ENV PATH=/usr/local/bin:/root/.local/bin:/tmp/.local/bin:$PATH # Install system dependencies # Bump to force a fresh apt-get upgrade past the build cache; keep in step with ../Dockerfile. -ARG APT_REFRESH=1 +ARG APT_REFRESH=2 RUN echo "apt refresh ${APT_REFRESH}" \ && apt-get update \ && apt-get upgrade -y \ @@ -66,7 +66,7 @@ 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.13.6/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.8/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 @@ -82,7 +82,7 @@ RUN mkdir -p /tmp/windmill/cache && \ rm -rf /tmp/build_cache && \ mkdir -p -m 777 /tmp/windmill/cache/uv -COPY --from=oven/bun:1.4.4 /usr/local/bin/bun /usr/bin/bun +COPY --from=oven/bun:1.4.5 /usr/local/bin/bun /usr/bin/bun # Install windmill CLI (node symlink needed for bun install) RUN ln -s /usr/bin/bun /usr/bin/node \ diff --git a/docs/auth-surface.md b/docs/auth-surface.md index 5e2070f3f7..0b7b7e9827 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -18,13 +18,13 @@ Symbols, not line numbers, are cited: they drift less. token's 7 days therefore has no row left to delete: what ends a user's access calls `revoke_mcp_oauth_grants` (`windmill-api-users`), which also deletes grants without a live token and codes not yet exchanged — a password change or reset, disabling or deleting the - account, offboarding, SCIM deactivation and removal, and (for the grants bound to that - workspace) removal from a workspace. The grant lock (`lock_mcp_oauth_grants`) is the user's - `password` row, shared while issuing a grant and exclusive while revoking, because every path + account, leaving the instance, offboarding, SCIM deactivation and removal, and (for the + grants bound to that workspace) removal from a workspace. The grant lock + (`lock_mcp_oauth_grants`) is the user's `password` row, shared while issuing a grant and exclusive while revoking, because every path that changes a user locks that row before their tokens: a refresh takes it, then its access-token row, then its grant, the order the trigger also follows. A new path that writes a - user's tokens and may revoke must lock that row first too. `leave_workspace` and `leave_instance` - delete no tokens and revoke nothing. + user's tokens and may revoke must lock that row first too. `leave_workspace` deletes no tokens + and revokes nothing; `leave_instance` deletes every token of the account, as `delete_user` does. - **Sessions** are `token` rows with `label='session'` plus the HttpOnly `token` cookie, minted only by `create_session_token` (`windmill-api-users/src/users.rs`). `GET /api/users/refresh_token` mints one for any non-job token but returns plain text, no redirect. @@ -140,11 +140,10 @@ Symbols, not line numbers, are cited: they drift less. the same (or the owner is a superadmin) and it decrypts. So a target set A → B → A, or a removal and re-add, voids it whatever the clocks say. A superadmin with no membership is bound through the credential making the request instead: the insert requires its `token` row to - still exist, and `delete_user`, offboarding and SCIM removal delete an account's tokens, so an - address deleted that way and re-created during the call does not inherit the connection (a JWT, - having no row, cannot connect a workspace its owner is not a member of). `leave_instance` - deletes only the `password` row, leaving the tokens and the memberships, which is not covered. - Neither is a member's connect across an account re-creation: an address is not expected to pass + still exist, and `delete_user`, `leave_instance`, offboarding and SCIM removal delete an + account's tokens, so an address deleted that way and re-created during the call does not + inherit the connection (a JWT, having no row, cannot connect a workspace its owner is not a + member of). A member's connect across an account re-creation is not covered: an address is not expected to pass to another person. A disconnect empties and stamps the row (inserting one if needed) rather than deleting it, `connected_at` is when a connect started, and the connect's upsert leaves a row stamped after that alone, so an older connect cannot undo diff --git a/docs/feature-telemetry.md b/docs/feature-telemetry.md index 0589d79b16..ed2ca255e1 100644 --- a/docs/feature-telemetry.md +++ b/docs/feature-telemetry.md @@ -4,13 +4,14 @@ anonymous usage-stats payload. It answers "does anyone use this, and which variant do they pick" without any identifying data leaving the instance. -It currently carries 100 registered actions across forty features (`access_view`, `ai_session`, `ai_chat`, +It currently carries 111 registered actions across forty-three features (`access_view`, `ai_session`, `ai_chat`, +`autoscaling_diagnostics`, `code_mode`, `ai_fix`, `ai_agent`, `ai_decision`, `ai_agent_eval`, `app_sandbox`, `datatable`, `db_manager`, `flow_editor`, `flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `sharing`, `debugger`, `trigger`, `command_script`, `mcp`, `mcp_workspace`, `mcp_external_client`, `hub_script`, `usage_meter`, `sso_groups_claim`, `cloud_trial_offer`, `job_token_scopes`, `worker_draining`, `worker_group`, `worker_resource_stats`, `dev_workspace_isolation`, `slack_agent`, `variable_expiration`, -`external_secret_ref`, `anthropic_federation`, `deployment_request`, `fork_roles`, `git_sync_review`, `workspace_webhook`). Nearly all of the +`external_secret_ref`, `anthropic_federation`, `vertex_workload_identity`, `deployment_request`, `fork_roles`, `git_sync_review`, `workspace_webhook`). Nearly all of the product is uninstrumented, so new user-facing work is the opportunity to change that. ## When to instrument diff --git a/docs/operator-builder-rights.md b/docs/operator-builder-rights.md index 08ce69b6ba..d2786df83c 100644 --- a/docs/operator-builder-rights.md +++ b/docs/operator-builder-rights.md @@ -56,6 +56,9 @@ permissions: `worker_flow` then applies to the step job. So composing a path is enough to run it, and to run it as whoever it runs as: `validate_operator_composed_flow` re-checks each path under the caller's RLS. This is the general case; the one below is on top of it, not instead of it. + A Hub step has no workspace row to read, so it is collected apart and held to the run-time rule + for naming a Hub path (`check_can_name_runnable`) against the builder: Hub steps follow the + `code` capability, and preset handlers are allowed to every role. - **the `(path, hash)` of every version-pinned step**. A step carrying a `hash` is dispatched by that hash alone, with the path beside it never consulted, so a readable path paired with another script's hash still runs that other script. @@ -88,7 +91,8 @@ that function. 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 +referenced path under the caller's RLS and holds a Hub one to `check_can_name_runnable`, as in a +flow, so Hub steps follow the `code` capability. 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>`, `flow/<path>` and @@ -152,7 +156,7 @@ the bundle same-origin with the session of whoever opens it. A builder's draft i 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 +a draft naming a runnable the builder cannot read, or a Hub one its role may not name, 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 diff --git a/docs/operator-write-rights.md b/docs/operator-write-rights.md index 5fda1547f0..89d5b15830 100644 --- a/docs/operator-write-rights.md +++ b/docs/operator-write-rights.md @@ -54,6 +54,17 @@ 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. +## Hub paths in triggers and schedules + +Whatever write rights they hold, a member without `code` cannot save a new Hub path into a trigger, +a schedule or a WebSocket capture config (`check_new_hub_paths`). Paths already saved keep working, +and are not rechecked when the trigger or schedule is edited, even when the edit moves one between +a trigger's fields (an error handler to the main script) or among a schedule's handlers; a handler +cannot take the schedule's Hub target. The edit makes the editor its run-as identity unless they +may keep the stored one (admins, `wm_deployers`), so a saved Hub path then runs as the editor, with +the arguments they save: accepted so that rows a member with `code` set up stay editable, since the +choice of which Hub code runs stays with that member. + ## Drafts An operator may save a draft of a kind they could deploy, and no other: a resource or variable diff --git a/docs/reusable-ai-agents.md b/docs/reusable-ai-agents.md index 3d3163470f..74739586af 100644 --- a/docs/reusable-ai-agents.md +++ b/docs/reusable-ai-agents.md @@ -8,6 +8,23 @@ agent, and edits to the agent propagate to every linked step. The `ai_agent` resource type is defined in the hub (windmill-integrations) and synced into every workspace via the standard cached-resource-type sync, like other built-in types. +## Running an agent on its own + +A saved agent also runs without any flow of the author's: from its deployed page, through +`POST /w/{workspace}/jobs/run/agent/{path}` (scope `jobs:run:agents:<path>`), from a Slack channel +it is shared in, from a full-code app, and from the AI session's run tools. All of them go through +`windmill-api/src/agent_runs.rs`, which reads the agent and runs it as a **one-step flow** +(`agent_step_flow`, step id `__wm_agent_root`). Every run drops the agent's saved `memory_id` and +`previous_messages` step inputs: the message, attachments and any `previous_messages` come from +the run's input. A run with a `memory_id` is a turn of a conversation, filed under `<path>.chat` +and run with chat input enabled. The agent editor's chat is different: it previews the draft as a +flow preview of the same one step (`agentChatFlow`), not through `agent_runs.rs`. + +Since the run is a flow, everything written for flow runs and chat flows applies to it as well: +conversations, the running-turn check, approvals and questions. A change to one of those paths +must keep working for this one-step shape, and can be tested from the agent's deployed page as +well as from a flow. + ## Rigid linking `FlowModuleValue::AIAgent` has an optional `agent` field holding the resource path, plus a @@ -156,6 +173,42 @@ older editor baked into `memory` stays a fallback behind the run's id until the *Keep as memory id* or *Use the run's memory id*. In a chat flow it is dropped on save, since the conversation id always took precedence there. +## One running turn per memory id + +Two runs with the same memory id would each read the memory at start and the last to finish would +overwrite the other's turn, so a run is refused while another one is working on its id. + +- **Claim.** `set_flow_memory_id` claims `ai_memory_turn (workspace_id, memory_id) -> job_id` in + the push transaction, for every run that carries a run memory id, chat or not. A claim whose job + is still in `v2_job_queue` refuses the push with a 409 whose body names the running turn; one + whose job left the queue is taken over, and the monitor deletes it. For a chat flow the + conversation check runs first, since its refusal carries the `user_seq` the chat follows. The + claim covers the run memory id only: a step's own `memory_id` is evaluated on the worker, after + the push, and stays unguarded. +- **A parked run hands it over.** A holder whose agent parked (answered while its background jobs + run, or waiting on an approval or a question) as the run's last top-level step, where the run + is at, is not refused against: the new run takes the conversation (`hand_over_parked_turn`). + After that step the run ends, so nothing of it can write the memory or the chat beside the new + turn; a step after the agent, or one in a parallel branch, would, so such a run is refused as a + working one, its 409 saying why, and `take_over` stays the way through. Under the parked agent's queue row lock, its `suspend` is + zeroed and its checkpoint marked `handed_over`, which keeps the monitor's wake and an answer from + resuming it too. Its background jobs move onto the claim row (`handed_jobs`, by flow step id) and + the new run's agent of that step adopts them when it starts. The parked agent wakes, refuses an + open approval or skips a question without a chat row, and ends with the answer it had, writing + no memory: it saved its memory when it parked, with the open request's calls already reading as + left unanswered. The flow chat's own running-turn check lets a parked turn through the same way. +- **Take over.** `take_over=true` on a run cancels the run holding the id, then waits up to 40s + for it to leave the queue before pushing (`take_over_memory_turn`). Only who started that run, or + an admin, can do it, and a restricted token only with an unconfined `jobs:cancel` scope, since a + uuid memory id is not confined to the flow being run. The holder is stopped before the new run is + validated, so a new run refused for another reason leaves the memory id with no turn. App runs + refuse `take_over`. +- **History on stop.** A cancelled agent writes its managed memory before it returns, so the next + turn starts from what this one reached. Every place it stops at has each tool call answered; one + stopped before its first reply keeps the unanswered message, and the next turn's message follows + it. No compaction runs there, since it would call the model inside the cancel's + grace period. An agent cancelled while parked is completed without running, and saves nothing. + ## Approval and questions Two things park the agent rather than run: a call of a tool with `requires_approval` (flow module @@ -201,12 +254,62 @@ Both live in `windmill-worker/src/ai/pause.rs`. inside a loop or branch is answered from its graph node. The chat transcript of a chat flow records neither the request nor its answer. +## Background tools + +A `flowmodule` tool with `background: true` is answered as soon as its job is queued ("started in +the background as job X"), and the agent keeps working. The job's result reaches the model later as +a user message tagged with the call's `tool_call` action, since the call itself was already +answered. Its outcome in `agent_actions_success` is `null` until then, set in place by position. + +With `background_after_secs: N` instead, the call is waited on like a foreground one, and still +unfinished N seconds after it was queued it is answered the same way ("not finished after Ns") and +continues in the background. Such a job never runs in the agent's own process, which could not release the worker +while it ran, so it needs another worker free: with none, it only starts once the agent parks. + +- **Parking.** The loop checks for finished jobs before each model call. When the model answers + with jobs still running, the agent parks like it does for an approval (`suspend = 1`, the same + checkpoint table) instead of ending, with the jobs in the checkpoint row's `waiting_on`. The park + first checks, under its queue row lock, whether one already finished, and delivers it instead. +- **Waking.** Every monitor pass zeroes the `suspend` of a parked agent with a completed job in + `waiting_on`, so a result waits at most one pass (10s by default) once its job ends. Not + `record_child_completion`, although tool jobs are the agent's children: when it wakes a parent it + clears all of its pending ids, which fits a workflow-as-code round but would drop the agent's + other background jobs. +- **Iterations.** The model call that follows a background result reuses the iteration of the + answer it revisits, so waiting never runs an agent out of iterations. An agent that does run out + cancels the jobs still running. With structured output, an earlier structured answer stands unless + the model gives another. +- **With an approval.** While an approval is open, `waiting_on` is empty: results wait for the + answer. An answer the row accepts while the agent waits on background jobs only is marked read on + resume, so it cannot answer a later request. +- **Limits.** A nested agent runs its background tools in the foreground, since it cannot park. The + job is never reserved for the agent's own worker. Like a foreground tool, a job that never + finishes (a tag no worker serves) keeps the agent waiting, here parked and re-checked hourly. + ## Drafts The agent editor edits the resource through a **per-user resource draft** (`draft` table, `item_kind = 'resource'`), autosaved by `useAgentDraft` and deployed by the editor's own Deploy -button. It is the same draft row the generic resource editor writes and the Review & Deploy page -lists, so an agent can be deployed from any of them. +button. It is the same draft row the resource editor's *Edit as JSON* view writes and the Review & +Deploy page lists, so an agent can be deployed from any of them. `/drafts/list` reports a resource +draft's `resource_type` (the deployed row's, which a deploy keeps, else the one the draft names), so +a listing tells an agent's draft apart without reading it; for an agent it also reports the +description as the summary and the path the draft names as `draft_path`. + +Agent drafts are private to their author, like every resource draft: a resource draft can hold a +credential, and sharing is decided by draft kind (`shares_drafts_across_users`). + +The agent editor carries the same draft controls as the script and flow editors: the autosave +indicator (save state, *Reset to deployed*, the auto-save toggle), a *Diff* button, Ctrl/Cmd+S, and +the draft prompts (`DraftEditorModals`: a refused save, a draft older than the last deploy). With +auto-save off, closing the dialog or leaving the page asks before dropping edits that were never +saved. A session's tab has nothing that could ask, so there the agent saves every edit whatever the +toggle says, and its indicator leaves the toggle out. + +A draft never carries the identity the agent runs as, so every write of one restates the deployed +agent's `on_behalf_of` with `preserve_on_behalf_of`: a draft deploy, the session's +`deploy_workspace_item` and *Edit as JSON*'s Save. The server keeps it for a caller allowed to keep +another identity; anyone else's write makes it theirs. A flow does not wait for that deploy to see the draft: diff --git a/docs/validation.md b/docs/validation.md index 74e9cf5677..9e0e74d7c5 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -29,6 +29,7 @@ After all code changes are done, run `./update_sqlx.sh` from `backend/` to regen | When | Command | Time | |---|---|---| | During iteration | `npm run check:fast` | ~2s | +| During iteration | `npm run lint` (oxlint, `.oxlintrc.json`) | <1s | | Final PR validation | `npm run check` | ~50s | | After backend API changes | `npm run generate-backend-client` first | | diff --git a/docs/workspace-roles.md b/docs/workspace-roles.md index 8bae28309a..02db77c3f8 100644 --- a/docs/workspace-roles.md +++ b/docs/workspace-roles.md @@ -46,8 +46,9 @@ prefixes is gated for free. It lets through the dependency-lock and dynamic-sele preview routes (`run/preview`, `run_inline/preview`, `run_wait_result/preview`) check `run` in their handlers instead, after the exemption that lets a running job's SDK send a data table query there, since jobs a view-only member owns still run as them. Callers that push -without the router check `check_role_can_run` themselves: the MCP per-runnable tools, eval -experiment runs and members-only Slack agent shares (which run as the asking member). Resuming or approving a suspended step is not a run. Schedules and triggers keep +without the router check `check_role_can_run` themselves: the MCP per-runnable tools (which +`tools/list` also omits for such a role, along with the run endpoint tools), eval +experiment runs and members-only Slack agent shares (which run as the asking member). An MCP session token and the in-app AI session hold such a member to read-only, so neither offers a run tool. Resuming or approving a suspended step is not a run. Schedules and triggers keep their own rights, apps run their runnables on the app's policy and are not gated, and a job started by a schedule or trigger acts as its owner, so from inside it a view-only owner cannot start further runs through the API either. @@ -78,6 +79,12 @@ returns `FULL` for an unrestricted or admin caller without reading the role), so derived from the role: a stale flag lets a restricted member through. The authentication cache holds it for up to 120s. +`ApiAuthed::capabilities` is the role itself, read for each request before its handler runs, so a +capability check inside a save's transaction, the Hub rule included, never needs a second +connection. It is read from the role caches and never stored with the cached login: storing it +there would need every role change to clear the login on every server, running jobs' tokens +included. An identity built outside a request has none, and `caller_capabilities` reads the role. + `usr.operator` is kept as "this role cannot write code", which is what clients that predate roles read it as. A member's role is `usr.workspace_role`, or, while that is NULL, `operator` / `developer` from `usr.operator`: rows written by paths that know nothing of roles stay meaningful. diff --git a/frontend/.eslintrc.cjs b/frontend/.eslintrc.cjs deleted file mode 100644 index 18e962c6bb..0000000000 --- a/frontend/.eslintrc.cjs +++ /dev/null @@ -1,23 +0,0 @@ -module.exports = { - root: true, - parser: '@typescript-eslint/parser', - extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'], - plugins: ['svelte3', '@typescript-eslint'], - ignorePatterns: ['*.cjs'], - overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }], - settings: { - 'svelte3/typescript': () => require('typescript') - }, - parserOptions: { - sourceType: 'module', - ecmaVersion: 2019 - }, - env: { - browser: true, - es2017: true, - node: true - }, - rules: { - 'no-console': ['log', { allow: ['warn', 'error'] }] - } -} diff --git a/frontend/.oxlintrc.json b/frontend/.oxlintrc.json new file mode 100644 index 0000000000..dcdfd56400 --- /dev/null +++ b/frontend/.oxlintrc.json @@ -0,0 +1,49 @@ +{ + "$schema": "./node_modules/oxlint/configuration_schema.json", + "plugins": ["eslint", "typescript", "unicorn", "oxc"], + "categories": { + "correctness": "error" + }, + "env": { + "browser": true, + "node": true, + "es2024": true + }, + "ignorePatterns": ["src/lib/monaco_workers/graphql.worker.bundle.js", "static/**"], + "rules": { + // Svelte 5 reads a value in `$effect` to track it (`x && untrack(...)`, `;[x]`). + "no-unused-expressions": "off", + // `$store = $store` is how a mutated store is told to notify. + "no-self-assign": "off", + // tsc's `noUnusedLocals` covers locals; what is left is unused params and catch bindings. + "no-unused-vars": "off", + // Cosmetic: no runtime effect, so they only add churn. + "no-useless-escape": "off", + "no-useless-rename": "off", + "no-extra-boolean-cast": "off", + "typescript/prefer-as-const": "off", + "typescript/no-wrapper-object-types": "off", + "typescript/no-non-null-asserted-optional-chain": "off", + "typescript/no-this-alias": "off", + "unicorn/no-useless-fallback-in-spread": "off", + "unicorn/no-useless-spread": "off", + "unicorn/no-useless-length-check": "off", + "unicorn/no-new-array": "off", + "unicorn/no-empty-file": "off", + "unicorn/prefer-string-starts-ends-with": "off", + // Stripping control characters is what those regexes are for. + "no-control-regex": "off", + // Exports a deliberate thenable. + "unicorn/no-thenable": "off" + }, + "overrides": [ + { + "files": ["**/*.test.ts", "**/*.spec.ts"], + "rules": { + // A throw there fails the test, which is the point. + "no-unsafe-optional-chaining": "off", + "require-yield": "off" + } + } + ] +} diff --git a/frontend/package-lock.json b/frontend/package-lock.json index f5d0e7fe90..b94def4017 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.866.0", + "version": "1.880.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.866.0", + "version": "1.880.1", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { @@ -20,6 +20,7 @@ "@codingame/monaco-vscode-standalone-languages": "=25.0.0", "@codingame/monaco-vscode-standalone-typescript-language-features": "=25.0.0", "@floating-ui/core": "^1.3.1", + "@fontsource-variable/jetbrains-mono": "^5.3.0", "@jitl/quickjs-wasmfile-release-sync": "^0.32.0", "@json2csv/plainjs": "^7.0.6", "@leeoniya/ufuzzy": "^1.0.8", @@ -76,6 +77,9 @@ "rehype-github-alerts": "^3.0.0", "rehype-raw": "^7.0.0", "rehype-sanitize": "^6.0.0", + "rehype-stringify": "^10.0.1", + "remark-parse": "^11.0.0", + "remark-rehype": "^11.1.2", "rfc4648": "^1.5.3", "runed": "^0.36.0", "style-to-object": "^0.4.1", @@ -90,6 +94,7 @@ "svelte-range-slider-pips": "^2.3.1", "svelte-splitpanes": "^8.0.9", "tailwind-merge": "^1.13.2", + "unified": "^11.0.5", "unist-util-visit": "^5.0.0", "vscode": "npm:@codingame/monaco-vscode-extension-api@=25.0.0", "vscode-languageclient": "~9.0.1", @@ -110,7 +115,7 @@ "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.4", + "windmill-utils-internal": "1.8.6", "xterm": "^5.3.0", "xterm-readline": "^1.1.2", "y-monaco": "^0.1.4", @@ -133,18 +138,14 @@ "@types/d3-zoom": "^3.0.3", "@types/lodash": "^4.14.195", "@types/vscode": "^1.83.5", - "@typescript-eslint/eslint-plugin": "^5.59.8", - "@typescript-eslint/parser": "^5.60.0", "autoprefixer": "^10.4.13", "cssnano": "^6.0.1", "dts-bundle-generator": "^9.5.1", - "eslint": "^8.47.0", - "eslint-config-prettier": "^8.6.0", - "eslint-plugin-svelte": "^2.45.1", "fake-indexeddb": "^6.2.5", "jsdom": "^29.1.1", "json-refs": "^3.0.15", "json-schema-to-zod": "^2.7.0", + "oxlint": "1.93.0", "path-browserify": "^1.0.1", "postcss": "^8.4.49", "postcss-load-config": "^4.0.1", @@ -1098,106 +1099,6 @@ "@csstools/css-tokenizer": "^2.4.1" } }, - "node_modules/@eslint-community/eslint-utils": { - "version": "4.9.0", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.0.tgz", - "integrity": "sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" - } - }, - "node_modules/@eslint-community/regexpp": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.1.tgz", - "integrity": "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.0.0 || ^14.0.0 || >=16.0.0" - } - }, - "node_modules/@eslint/eslintrc": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", - "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ajv": "^6.12.4", - "debug": "^4.3.2", - "espree": "^9.6.0", - "globals": "^13.19.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.1.0", - "minimatch": "^3.1.2", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@eslint/eslintrc/node_modules/ajv": { - "version": "6.15.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", - "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/@eslint/eslintrc/node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@eslint/eslintrc/node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/@eslint/js": { - "version": "8.57.1", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", - "integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - } - }, "node_modules/@exodus/bytes": { "version": "1.15.1", "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz", @@ -1241,6 +1142,15 @@ "integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==", "license": "MIT" }, + "node_modules/@fontsource-variable/jetbrains-mono": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz", + "integrity": "sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, "node_modules/@glideapps/ts-necessities": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/@glideapps/ts-necessities/-/ts-necessities-2.2.3.tgz", @@ -1270,57 +1180,6 @@ "typescript": "^5.x" } }, - "node_modules/@humanwhocodes/config-array": { - "version": "0.13.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", - "integrity": "sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==", - "deprecated": "Use @eslint/config-array instead", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@humanwhocodes/object-schema": "^2.0.3", - "debug": "^4.3.1", - "minimatch": "^3.0.5" - }, - "engines": { - "node": ">=10.10.0" - } - }, - "node_modules/@humanwhocodes/config-array/node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/@humanwhocodes/module-importer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", - "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12.22" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@humanwhocodes/object-schema": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", - "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", - "deprecated": "Use @eslint/object-schema instead", - "dev": true, - "license": "BSD-3-Clause" - }, "node_modules/@iconify/types": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz", @@ -1671,6 +1530,329 @@ "url": "https://github.com/sponsors/Boshen" } }, + "node_modules/@oxlint/binding-android-arm-eabi": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.93.0.tgz", + "integrity": "sha512-KKw70pbD5Pvq3G2lJ+WQ71XPMjCmg37rkSe2+mDqCRP3PoTSdDMuEi4UOnE8JBtyNM7bek61EC2s0Jt7S7u+Sg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-android-arm64": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.93.0.tgz", + "integrity": "sha512-fvr1fTUZGelwRxKDt64pf28aL1WaWgviwz3X+E/FcRYvrlEahH0NECRz/c1SY+K+KWmZk5uAf6h1kQnyBkp/2A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-darwin-arm64": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.93.0.tgz", + "integrity": "sha512-VdvSN9JRf4Es6ZzoAdvEeh8tgKdw8L4H82WmA8MMPVfPdZGCwE/nI27Z1HrRHYQhPxOh4kmnxQEioSUFrOvDaw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-darwin-x64": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.93.0.tgz", + "integrity": "sha512-QR1V890Ml0YGRG0F/iV0K9igG+pOhe+VWd+aZnxY849rRHZf3F2gEoQks5+GVHf105X9Mh/6HdShTP5juekG2g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-freebsd-x64": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.93.0.tgz", + "integrity": "sha512-jDfIbi30zZaKi+rTvig3sge+Xhi8pFFSgHxb0jzovc4qh8ETm/irKV9c7N/JsuwnYc5sbvf4IC8w1vQQ0IL+BA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm-gnueabihf": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.93.0.tgz", + "integrity": "sha512-qtxZ714ND/koFgVH00QgxlzZiIbRPmguaPhnHRU5DFFtrtEdOrSnZD4U/H2AzXrXkZ59eQbMBnJwbum5XohrIQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm-musleabihf": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.93.0.tgz", + "integrity": "sha512-5pJ9NjMvH7WMUqXB6bTTOSemBm39w2cod27Hu3+Yom/GhbTeNXlYcpDx1o4CgBP6fhp0YHG66TNdVaUm6sHjsA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm64-gnu": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.93.0.tgz", + "integrity": "sha512-pRf+7jtbt2fHE23SX7qBxRgnBZicUgsoCK1PVIjnOk+t3a6UBkpt/GrKI99WlxsKUxftz/5nv/kfKvScmYywkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm64-musl": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.93.0.tgz", + "integrity": "sha512-zM8Fd/K8sqGvsBcJBZ3oVZ3ctGWbszA08IaGt5gFFF5RcunppAI/ZnAXbouABvnWeJ//S44KKlfPZnDDbeiphg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-ppc64-gnu": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.93.0.tgz", + "integrity": "sha512-7qKCnvhZKDXJG2pdbLazd2hw4FxjJHbZOFrrbzyy5PdHfPLH9vnNUa1le01A8uItZuYKPBPncH+HCoEiFT4SgA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-riscv64-gnu": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.93.0.tgz", + "integrity": "sha512-2pgulxC6G8V5wE750NJE/fRkf9aO6i6yoj10wyaR2EdiNtan4OemsOtsQ0ZTXGdY8Q3IoTmlND3GYvjJsvikYg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-riscv64-musl": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.93.0.tgz", + "integrity": "sha512-yWsn6Gg2PnGG5jlyDz5+pHGiMTMiy4adaa4WRMzDgzB8efaShk1JMmTHIBSVLQMh0tYXRs4CN5uJCO79r4Mi4g==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-s390x-gnu": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.93.0.tgz", + "integrity": "sha512-WCn5plwp/ezS2RDPQKp0/EXEVRr9/dDexUdRKmsMFqzNM5xBSZ1wbsi3PuMk1VfkMRnI5BuazCsziCWMXRDOlw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-x64-gnu": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.93.0.tgz", + "integrity": "sha512-F2CGjb9LAkzH+IYTZSzd1klQ1vk5z6Utjax64WeLByCkYXbVDbsun+Oy2hLfW2MDSKCvW+jwy/9ld0EPgdeu+A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-x64-musl": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.93.0.tgz", + "integrity": "sha512-plf5DE2objcG8Tf7mXRuRa8tT8rzDkpjqXQtKoGsKHWkpgsialbON1+cCtoSEUTVbQUjXvuAm8vV9+3rR0yCBw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-openharmony-arm64": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.93.0.tgz", + "integrity": "sha512-Kp2yJrKvoTe9FfKdO/xwLNUbs2bYTMKx0+aoQD1s0h/Tx0kSgtHSdGmrk8tTKdluosjFbo88qYRIaNIX43AfFw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-arm64-msvc": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.93.0.tgz", + "integrity": "sha512-vigjcHCFsR6KjnWTEVfaCxcMYapEuaK9FZa1MpewwQ1S+Xud3v0okfkj1RySsD6RF1NRHIjSlQSalTnKIaj3nA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-ia32-msvc": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.93.0.tgz", + "integrity": "sha512-0Ot3BEe/AAr2/uQhe55r8CmPlperYk2mQmxdutOru7oU0kir6IiEVHb1TG3GORRlfra97lPHVDLhgmihiKzLrg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-x64-msvc": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.93.0.tgz", + "integrity": "sha512-ZzzIIVs/Qkm8trUWYKF0OYub5ALlv50/3gsEZbKAvWgz+yNJX6uRmQ8ySPXU2Q0/Y9m4JCOjhpmC8XUYbPHX5Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, "node_modules/@paralleldrive/cuid2": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.3.1.tgz", @@ -2602,13 +2784,6 @@ "license": "MIT", "peer": true }, - "node_modules/@types/semver": { - "version": "7.7.1", - "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.7.1.tgz", - "integrity": "sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/trusted-types": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", @@ -2629,202 +2804,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@typescript-eslint/eslint-plugin": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.62.0.tgz", - "integrity": "sha512-TiZzBSJja/LbhNPvk6yc0JrX9XqhQ0hdh6M2svYfsHGejaKFIAGd9MQ+ERIMzLGlN/kZoYIgdxFV0PuljTKXag==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/regexpp": "^4.4.0", - "@typescript-eslint/scope-manager": "5.62.0", - "@typescript-eslint/type-utils": "5.62.0", - "@typescript-eslint/utils": "5.62.0", - "debug": "^4.3.4", - "graphemer": "^1.4.0", - "ignore": "^5.2.0", - "natural-compare-lite": "^1.4.0", - "semver": "^7.3.7", - "tsutils": "^3.21.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "@typescript-eslint/parser": "^5.0.0", - "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/parser": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz", - "integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "@typescript-eslint/scope-manager": "5.62.0", - "@typescript-eslint/types": "5.62.0", - "@typescript-eslint/typescript-estree": "5.62.0", - "debug": "^4.3.4" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/scope-manager": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz", - "integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "5.62.0", - "@typescript-eslint/visitor-keys": "5.62.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/type-utils": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.62.0.tgz", - "integrity": "sha512-xsSQreu+VnfbqQpW5vnCJdq1Z3Q0U31qiWmRhr98ONQmcp/yhiPJFPq8MXiJVLiksmOKSjIldZzkebzHuCGzew==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/typescript-estree": "5.62.0", - "@typescript-eslint/utils": "5.62.0", - "debug": "^4.3.4", - "tsutils": "^3.21.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "*" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/types": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz", - "integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/typescript-estree": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz", - "integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "@typescript-eslint/types": "5.62.0", - "@typescript-eslint/visitor-keys": "5.62.0", - "debug": "^4.3.4", - "globby": "^11.1.0", - "is-glob": "^4.0.3", - "semver": "^7.3.7", - "tsutils": "^3.21.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/utils": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.62.0.tgz", - "integrity": "sha512-n8oxjeb5aIbPFEtmQxQYOLI0i9n5ySBEY/ZEHHZqKQSFnxio1rv6dthascc9dLuwrL0RC5mPCxB7vnAVGAYWAQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.2.0", - "@types/json-schema": "^7.0.9", - "@types/semver": "^7.3.12", - "@typescript-eslint/scope-manager": "5.62.0", - "@typescript-eslint/types": "5.62.0", - "@typescript-eslint/typescript-estree": "5.62.0", - "eslint-scope": "^5.1.1", - "semver": "^7.3.7" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "5.62.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz", - "integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "5.62.0", - "eslint-visitor-keys": "^3.3.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, "node_modules/@typescript/native-preview": { "version": "7.0.0-dev.20260218.1", "resolved": "https://registry.npmjs.org/@typescript/native-preview/-/native-preview-7.0.0-dev.20260218.1.tgz", @@ -3203,16 +3182,6 @@ "node": ">=0.4.0" } }, - "node_modules/acorn-jsx": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, "node_modules/ag-charts-community": { "version": "9.3.2", "resolved": "https://registry.npmjs.org/ag-charts-community/-/ag-charts-community-9.3.2.tgz", @@ -3384,6 +3353,7 @@ "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=8" } @@ -3593,6 +3563,7 @@ "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -3603,7 +3574,8 @@ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/braces": { "version": "3.0.3", @@ -3792,6 +3764,7 @@ "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=6" } @@ -3950,23 +3923,6 @@ "node": ">=18" } }, - "node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, "node_modules/character-entities": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", @@ -3977,6 +3933,26 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/character-entities-html4": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", + "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/character-entities-legacy": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", + "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/chart.js": { "version": "4.5.1", "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz", @@ -4193,7 +4169,8 @@ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/confbox": { "version": "0.1.8", @@ -5223,13 +5200,6 @@ "node": ">=4.0.0" } }, - "node_modules/deep-is": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true, - "license": "MIT" - }, "node_modules/deepmerge": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", @@ -5359,6 +5329,7 @@ "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "path-type": "^4.0.0" }, @@ -5373,19 +5344,6 @@ "dev": true, "license": "MIT" }, - "node_modules/doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "esutils": "^2.0.2" - }, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/dom-serializer": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", @@ -5694,295 +5652,6 @@ "node": ">=6" } }, - "node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/eslint": { - "version": "8.57.1", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.1.tgz", - "integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==", - "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.2.0", - "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.57.1", - "@humanwhocodes/config-array": "^0.13.0", - "@humanwhocodes/module-importer": "^1.0.1", - "@nodelib/fs.walk": "^1.2.8", - "@ungap/structured-clone": "^1.2.0", - "ajv": "^6.12.4", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.2", - "debug": "^4.3.2", - "doctrine": "^3.0.0", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.3", - "espree": "^9.6.1", - "esquery": "^1.4.2", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", - "find-up": "^5.0.0", - "glob-parent": "^6.0.2", - "globals": "^13.19.0", - "graphemer": "^1.4.0", - "ignore": "^5.2.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "is-path-inside": "^3.0.3", - "js-yaml": "^4.1.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.4.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.1.2", - "natural-compare": "^1.4.0", - "optionator": "^0.9.3", - "strip-ansi": "^6.0.1", - "text-table": "^0.2.0" - }, - "bin": { - "eslint": "bin/eslint.js" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-compat-utils": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/eslint-compat-utils/-/eslint-compat-utils-0.5.1.tgz", - "integrity": "sha512-3z3vFexKIEnjHE3zCMRo6fn/e44U7T1khUjg+Hp0ZQMCigh28rALD0nPFBcGZuiLC5rLZa2ubQHDRln09JfU2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "semver": "^7.5.4" - }, - "engines": { - "node": ">=12" - }, - "peerDependencies": { - "eslint": ">=6.0.0" - } - }, - "node_modules/eslint-config-prettier": { - "version": "8.10.2", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.10.2.tgz", - "integrity": "sha512-/IGJ6+Dka158JnP5n5YFMOszjDWrXggGz1LaK/guZq9vZTmniaKlHcsscvkAhn9y4U+BU3JuUdYvtAMcv30y4A==", - "dev": true, - "license": "MIT", - "bin": { - "eslint-config-prettier": "bin/cli.js" - }, - "peerDependencies": { - "eslint": ">=7.0.0" - } - }, - "node_modules/eslint-plugin-svelte": { - "version": "2.46.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-svelte/-/eslint-plugin-svelte-2.46.1.tgz", - "integrity": "sha512-7xYr2o4NID/f9OEYMqxsEQsCsj4KaMy4q5sANaKkAb6/QeCjYFxRmDm2S3YC3A3pl1kyPZ/syOx/i7LcWYSbIw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.4.0", - "@jridgewell/sourcemap-codec": "^1.4.15", - "eslint-compat-utils": "^0.5.1", - "esutils": "^2.0.3", - "known-css-properties": "^0.35.0", - "postcss": "^8.4.38", - "postcss-load-config": "^3.1.4", - "postcss-safe-parser": "^6.0.0", - "postcss-selector-parser": "^6.1.0", - "semver": "^7.6.2", - "svelte-eslint-parser": "^0.43.0" - }, - "engines": { - "node": "^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/ota-meshi" - }, - "peerDependencies": { - "eslint": "^7.0.0 || ^8.0.0-0 || ^9.0.0-0", - "svelte": "^3.37.0 || ^4.0.0 || ^5.0.0" - }, - "peerDependenciesMeta": { - "svelte": { - "optional": true - } - } - }, - "node_modules/eslint-plugin-svelte/node_modules/lilconfig": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-2.1.0.tgz", - "integrity": "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/eslint-plugin-svelte/node_modules/postcss-load-config": { - "version": "3.1.4", - "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-3.1.4.tgz", - "integrity": "sha512-6DiM4E7v4coTE4uzA8U//WhtPwyhiim3eyjEMFCnUpzbrkK9wJHgKDT2mR+HbtSrd/NubVaYTOpSpjUl8NQeRg==", - "dev": true, - "license": "MIT", - "dependencies": { - "lilconfig": "^2.0.5", - "yaml": "^1.10.2" - }, - "engines": { - "node": ">= 10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - "peerDependencies": { - "postcss": ">=8.0.9", - "ts-node": ">=9.0.0" - }, - "peerDependenciesMeta": { - "postcss": { - "optional": true - }, - "ts-node": { - "optional": true - } - } - }, - "node_modules/eslint-plugin-svelte/node_modules/postcss-selector-parser": { - "version": "6.1.4", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.4.tgz", - "integrity": "sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "cssesc": "^3.0.0", - "util-deprecate": "^1.0.2" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/eslint-plugin-svelte/node_modules/yaml": { - "version": "1.10.2", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", - "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">= 6" - } - }, - "node_modules/eslint-scope": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", - "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/eslint-visitor-keys": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", - "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint/node_modules/ajv": { - "version": "6.15.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", - "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/eslint/node_modules/eslint-scope": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", - "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint/node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/eslint/node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT" - }, - "node_modules/eslint/node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, "node_modules/esm-env": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz", @@ -5998,24 +5667,6 @@ "esm-env": "^1.0.0" } }, - "node_modules/espree": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", - "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "acorn": "^8.9.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.4.1" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, "node_modules/esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", @@ -6030,62 +5681,6 @@ "node": ">=4" } }, - "node_modules/esquery": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", - "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "estraverse": "^5.1.0" - }, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/esquery/node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "estraverse": "^5.2.0" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esrecurse/node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estraverse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, "node_modules/estree-walker": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", @@ -6096,16 +5691,6 @@ "@types/estree": "^1.0.0" } }, - "node_modules/esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/event-target-shim": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", @@ -6217,20 +5802,6 @@ "node": ">= 6" } }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "dev": true, - "license": "MIT" - }, "node_modules/fast-safe-stringify": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", @@ -6290,19 +5861,6 @@ "reusify": "^1.0.4" } }, - "node_modules/file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", - "dev": true, - "license": "MIT", - "dependencies": { - "flat-cache": "^3.0.4" - }, - "engines": { - "node": "^10.12.0 || >=12.0.0" - } - }, "node_modules/fill-range": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", @@ -6322,6 +5880,7 @@ "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" @@ -6339,6 +5898,7 @@ "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "flatted": "^3.2.9", "keyv": "^4.5.3", @@ -6353,7 +5913,8 @@ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", "dev": true, - "license": "ISC" + "license": "ISC", + "peer": true }, "node_modules/focus-trap": { "version": "7.6.5", @@ -6440,7 +6001,8 @@ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", "dev": true, - "license": "ISC" + "license": "ISC", + "peer": true }, "node_modules/fsevents": { "version": "2.3.3", @@ -6574,6 +6136,7 @@ "deprecated": "Glob versions prior to v9 are no longer supported", "dev": true, "license": "ISC", + "peer": true, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -6608,6 +6171,7 @@ "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", + "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -6659,28 +6223,13 @@ "which": "bin/which" } }, - "node_modules/globals": { - "version": "13.24.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", - "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "type-fest": "^0.20.2" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/globby": { "version": "11.1.0", "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "array-union": "^2.1.0", "dir-glob": "^3.0.1", @@ -6717,13 +6266,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/graphemer": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", - "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", - "dev": true, - "license": "MIT" - }, "node_modules/graphlib": { "version": "2.1.8", "resolved": "https://registry.npmjs.org/graphlib/-/graphlib-2.1.8.tgz", @@ -6797,6 +6339,7 @@ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=8" } @@ -6953,6 +6496,29 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-to-html": { + "version": "9.0.6", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.6.tgz", + "integrity": "sha512-1SZUxCN3TtJAE7e2BQN2MBHsoZ1gnmi9GoCP5Di59CSWptIezSAW09yDZyVbanb78V9eCwrKqdQsjtfVTxYHWA==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "@types/unist": "^3.0.0", + "ccount": "^2.0.0", + "comma-separated-tokens": "^2.0.0", + "hast-util-whitespace": "^3.0.0", + "html-void-elements": "^3.0.0", + "mdast-util-to-hast": "^13.0.0", + "property-information": "^7.0.0", + "space-separated-tokens": "^2.0.0", + "stringify-entities": "^4.0.0", + "zwitch": "^2.0.4" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hast-util-to-parse5": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/hast-util-to-parse5/-/hast-util-to-parse5-8.0.0.tgz", @@ -6982,6 +6548,19 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/hast-util-whitespace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", + "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hastscript": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/hastscript/-/hastscript-9.0.1.tgz", @@ -7125,6 +6704,7 @@ "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">= 4" } @@ -7142,6 +6722,7 @@ "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" @@ -7180,6 +6761,7 @@ "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=0.8.19" } @@ -7205,6 +6787,7 @@ "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", "dev": true, "license": "ISC", + "peer": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" @@ -7317,16 +6900,6 @@ "node": ">=0.12.0" } }, - "node_modules/is-path-inside": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", - "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/is-plain-obj": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-1.1.0.tgz", @@ -7638,7 +7211,8 @@ "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/json-parse-even-better-errors": { "version": "2.3.1", @@ -7721,13 +7295,6 @@ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "license": "MIT" }, - "node_modules/json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "dev": true, - "license": "MIT" - }, "node_modules/json-stringify-pretty-compact": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/json-stringify-pretty-compact/-/json-stringify-pretty-compact-2.0.0.tgz", @@ -7828,6 +7395,7 @@ "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "json-buffer": "3.0.1" } @@ -7858,13 +7426,6 @@ "node": ">=6" } }, - "node_modules/known-css-properties": { - "version": "0.35.0", - "resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.35.0.tgz", - "integrity": "sha512-a/RAk2BfKk+WFGhhOCAYqSiFLc34k8Mt/6NWRI4joER0EYUzXIcFivjjnoD3+XU1DggLn/tZc3DOAgke7l8a4A==", - "dev": true, - "license": "MIT" - }, "node_modules/layout-base": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-1.0.2.tgz", @@ -8039,20 +7600,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, "node_modules/lib0": { "version": "0.2.114", "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.114.tgz", @@ -8382,6 +7929,7 @@ "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "p-locate": "^5.0.0" }, @@ -8437,13 +7985,6 @@ "dev": true, "license": "MIT" }, - "node_modules/lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true, - "license": "MIT" - }, "node_modules/lodash.truncate": { "version": "4.4.2", "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", @@ -9798,20 +9339,6 @@ "dev": true, "license": "MIT" }, - "node_modules/natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true, - "license": "MIT" - }, - "node_modules/natural-compare-lite": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare-lite/-/natural-compare-lite-1.4.0.tgz", - "integrity": "sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g==", - "dev": true, - "license": "MIT" - }, "node_modules/neo-async": { "version": "2.6.2", "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", @@ -10088,22 +9615,53 @@ "integrity": "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==", "license": "MIT" }, - "node_modules/optionator": { - "version": "0.9.4", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", - "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "node_modules/oxlint": { + "version": "1.93.0", + "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.93.0.tgz", + "integrity": "sha512-19JMsQFX+YvEbcUTFQxjTwhvs0Ibg0D6CFneSLgpwnACWcY/6LjhpGpkPodh0T5aIT1pjMTLlYaeBFzaVgugTA==", "dev": true, "license": "MIT", - "dependencies": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.5" + "bin": { + "oxlint": "bin/oxlint" }, "engines": { - "node": ">= 0.8.0" + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + }, + "optionalDependencies": { + "@oxlint/binding-android-arm-eabi": "1.93.0", + "@oxlint/binding-android-arm64": "1.93.0", + "@oxlint/binding-darwin-arm64": "1.93.0", + "@oxlint/binding-darwin-x64": "1.93.0", + "@oxlint/binding-freebsd-x64": "1.93.0", + "@oxlint/binding-linux-arm-gnueabihf": "1.93.0", + "@oxlint/binding-linux-arm-musleabihf": "1.93.0", + "@oxlint/binding-linux-arm64-gnu": "1.93.0", + "@oxlint/binding-linux-arm64-musl": "1.93.0", + "@oxlint/binding-linux-ppc64-gnu": "1.93.0", + "@oxlint/binding-linux-riscv64-gnu": "1.93.0", + "@oxlint/binding-linux-riscv64-musl": "1.93.0", + "@oxlint/binding-linux-s390x-gnu": "1.93.0", + "@oxlint/binding-linux-x64-gnu": "1.93.0", + "@oxlint/binding-linux-x64-musl": "1.93.0", + "@oxlint/binding-openharmony-arm64": "1.93.0", + "@oxlint/binding-win32-arm64-msvc": "1.93.0", + "@oxlint/binding-win32-ia32-msvc": "1.93.0", + "@oxlint/binding-win32-x64-msvc": "1.93.0" + }, + "peerDependencies": { + "oxlint-tsgolint": ">=7.0.2005", + "vite-plus": "*" + }, + "peerDependenciesMeta": { + "oxlint-tsgolint": { + "optional": true + }, + "vite-plus": { + "optional": true + } } }, "node_modules/p-limit": { @@ -10127,6 +9685,7 @@ "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "p-limit": "^3.0.2" }, @@ -10143,6 +9702,7 @@ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "yocto-queue": "^0.1.0" }, @@ -10159,6 +9719,7 @@ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=10" }, @@ -10208,6 +9769,7 @@ "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "callsites": "^3.0.0" }, @@ -10272,6 +9834,7 @@ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=8" } @@ -10282,6 +9845,7 @@ "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=0.10.0" } @@ -10344,6 +9908,7 @@ "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=8" } @@ -11135,6 +10700,7 @@ "integrity": "sha512-FARHN8pwH+WiS2OPCxJI8FuRJpTVnn6ZNFiqAM2aeW2LwTHWWmWgIyKC6cUo0L8aeKiF/14MNvnpls6R2PBeMQ==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12.0" }, @@ -11146,33 +10712,6 @@ "postcss": "^8.3.3" } }, - "node_modules/postcss-scss": { - "version": "4.0.9", - "resolved": "https://registry.npmjs.org/postcss-scss/-/postcss-scss-4.0.9.tgz", - "integrity": "sha512-AjKOeiwAitL/MXxQW2DliT28EKukvvbEWx3LBmJIRN8KfBGZbRTxNYW0kSqi1COiTZ57nZ9NW06S6ux//N1c9A==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss-scss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "engines": { - "node": ">=12.0" - }, - "peerDependencies": { - "postcss": "^8.4.29" - } - }, "node_modules/postcss-selector-parser": { "version": "6.0.10", "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz", @@ -11287,16 +10826,6 @@ "node": ">=10" } }, - "node_modules/prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8.0" - } - }, "node_modules/prettier": { "version": "3.6.2", "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", @@ -11764,6 +11293,21 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/rehype-stringify": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/rehype-stringify/-/rehype-stringify-10.0.1.tgz", + "integrity": "sha512-k9ecfXHmIPuFVI61B9DeLPN0qFHfawM6RsuX48hoqlaKSF61RskNjSm1lI8PhBEM0MRdLxVVm4WmTqJQccH9mA==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "hast-util-to-html": "^9.0.0", + "unified": "^11.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/remark-gfm": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz", @@ -11876,6 +11420,7 @@ "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=4" } @@ -11913,6 +11458,7 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", + "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -12500,6 +12046,20 @@ "node": ">=8" } }, + "node_modules/stringify-entities": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", + "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", + "license": "MIT", + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -12540,19 +12100,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/style-search": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/style-search/-/style-search-0.1.0.tgz", @@ -12870,6 +12417,7 @@ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "has-flag": "^4.0.0" }, @@ -13022,61 +12570,6 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, - "node_modules/svelte-eslint-parser": { - "version": "0.43.0", - "resolved": "https://registry.npmjs.org/svelte-eslint-parser/-/svelte-eslint-parser-0.43.0.tgz", - "integrity": "sha512-GpU52uPKKcVnh8tKN5P4UZpJ/fUDndmq7wfsvoVXsyP+aY0anol7Yqo01fyrlaWGMFfm4av5DyrjlaXdLRJvGA==", - "dev": true, - "license": "MIT", - "dependencies": { - "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.3", - "espree": "^9.6.1", - "postcss": "^8.4.39", - "postcss-scss": "^4.0.9" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/ota-meshi" - }, - "peerDependencies": { - "svelte": "^3.37.0 || ^4.0.0 || ^5.0.0" - }, - "peerDependenciesMeta": { - "svelte": { - "optional": true - } - } - }, - "node_modules/svelte-eslint-parser/node_modules/eslint-scope": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", - "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/svelte-eslint-parser/node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, "node_modules/svelte-exmarkdown": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/svelte-exmarkdown/-/svelte-exmarkdown-5.0.2.tgz", @@ -13227,21 +12720,6 @@ "svelte": "^4.2.19 || ^5.1.0" } }, - "node_modules/svelte/node_modules/@typescript-eslint/types": { - "version": "8.70.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.70.0.tgz", - "integrity": "sha512-asTOIYhDg4zdzOScCyaytrsV3cR6B4ecPQlXw/dJIm7J/MZTtCtfVII9JD8Geh4jTCrK/Xe6cg5UevoleMcoJQ==", - "license": "MIT", - "optional": true, - "peer": true, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, "node_modules/svelte/node_modules/esrap": { "version": "2.3.7", "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.3.7.tgz", @@ -13525,13 +13003,6 @@ "url": "https://github.com/privatenumber/terminal-columns?sponsor=1" } }, - "node_modules/text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "dev": true, - "license": "MIT" - }, "node_modules/thenify": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", @@ -13751,29 +13222,6 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, - "node_modules/tsutils": { - "version": "3.21.0", - "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", - "integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==", - "dev": true, - "license": "MIT", - "dependencies": { - "tslib": "^1.8.1" - }, - "engines": { - "node": ">= 6" - }, - "peerDependencies": { - "typescript": ">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta" - } - }, - "node_modules/tsutils/node_modules/tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", - "dev": true, - "license": "0BSD" - }, "node_modules/tunnel-agent": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", @@ -13787,32 +13235,6 @@ "node": "*" } }, - "node_modules/type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/type-flag": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/type-flag/-/type-flag-4.0.3.tgz", @@ -14719,21 +14141,11 @@ "integrity": "sha512-uHNL8F72/Tf96xF3hOHnPDjkEyqXw7fNjcPJiUhth9sTQkcwUIoJMOdwm8/cs+j9kKVRJ4tgNYMHEBLylazp6g==" }, "node_modules/windmill-utils-internal": { - "version": "1.8.4", - "resolved": "https://registry.npmjs.org/windmill-utils-internal/-/windmill-utils-internal-1.8.4.tgz", - "integrity": "sha512-s27Di5z/vonhMLd52P4i3iILQyty6ZIXYc89CCdkKZzseE6WiX/VMwdTF4nvNCjV3xN0WhAtXR+/PBhzarU2GQ==", + "version": "1.8.6", + "resolved": "https://registry.npmjs.org/windmill-utils-internal/-/windmill-utils-internal-1.8.6.tgz", + "integrity": "sha512-jzHhEZ3xSBf90zektXaAIhAu9wLo5RMtYshvjg5if8jjEJvWENd+WQzEbod8Sr+SzMUbmmF4ArefqN15f2XtHw==", "license": "Apache 2.0" }, - "node_modules/word-wrap": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", - "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/wordwrap": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index aa2892911b..571e26a1a2 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.866.0", + "version": "1.880.1", "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", @@ -11,11 +11,13 @@ "check:fast": "bun --bun svelte-fast-check --no-svelte-warnings --incremental", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --threshold warning", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", - "lint": "prettier --ignore-path .gitignore --check --plugin-search-dir=. . && eslint --ignore-path .gitignore .", + "lint": "oxlint", + "format:check": "prettier --ignore-path .gitignore --check --plugin-search-dir=. .", "format": "prettier --ignore-path .gitignore --write --plugin-search-dir=. .", "package": "svelte-package -o package && node scripts/package-system-prompts.js && node scripts/fix-svelte-module-imports.js", "generate-backend-client": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --useOptions --enums javascript --format false", "generate-backend-client-mac": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --useOptions --enums javascript", + "gen:display-catalog": "WM_GEN_DISPLAY_CATALOG=1 vitest run --project server src/lib/components/display/displayCatalogGen.test.ts", "gen:mcp-session": "WM_GEN_MCP_SESSION=1 vitest run --project server src/lib/components/copilot/chat/global/mcpSessionGen.test.ts", "pretest": "tsc --incremental -p tests/tsconfig.json", "filter-classes": "node filterTailwindClasses.js", @@ -36,18 +38,14 @@ "@types/d3-zoom": "^3.0.3", "@types/lodash": "^4.14.195", "@types/vscode": "^1.83.5", - "@typescript-eslint/eslint-plugin": "^5.59.8", - "@typescript-eslint/parser": "^5.60.0", "autoprefixer": "^10.4.13", "cssnano": "^6.0.1", "dts-bundle-generator": "^9.5.1", - "eslint": "^8.47.0", - "eslint-config-prettier": "^8.6.0", - "eslint-plugin-svelte": "^2.45.1", "fake-indexeddb": "^6.2.5", "jsdom": "^29.1.1", "json-refs": "^3.0.15", "json-schema-to-zod": "^2.7.0", + "oxlint": "1.93.0", "path-browserify": "^1.0.1", "postcss": "^8.4.49", "postcss-load-config": "^4.0.1", @@ -87,6 +85,7 @@ "@codingame/monaco-vscode-standalone-languages": "=25.0.0", "@codingame/monaco-vscode-standalone-typescript-language-features": "=25.0.0", "@floating-ui/core": "^1.3.1", + "@fontsource-variable/jetbrains-mono": "^5.3.0", "@jitl/quickjs-wasmfile-release-sync": "^0.32.0", "@json2csv/plainjs": "^7.0.6", "@leeoniya/ufuzzy": "^1.0.8", @@ -143,6 +142,9 @@ "rehype-github-alerts": "^3.0.0", "rehype-raw": "^7.0.0", "rehype-sanitize": "^6.0.0", + "rehype-stringify": "^10.0.1", + "remark-parse": "^11.0.0", + "remark-rehype": "^11.1.2", "rfc4648": "^1.5.3", "runed": "^0.36.0", "style-to-object": "^0.4.1", @@ -157,6 +159,7 @@ "svelte-range-slider-pips": "^2.3.1", "svelte-splitpanes": "^8.0.9", "tailwind-merge": "^1.13.2", + "unified": "^11.0.5", "unist-util-visit": "^5.0.0", "vscode": "npm:@codingame/monaco-vscode-extension-api@=25.0.0", "vscode-languageclient": "~9.0.1", @@ -177,7 +180,7 @@ "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.4", + "windmill-utils-internal": "1.8.6", "xterm": "^5.3.0", "xterm-readline": "^1.1.2", "y-monaco": "^0.1.4", diff --git a/frontend/scripts/ui_builder_artifact.json b/frontend/scripts/ui_builder_artifact.json index 6f0c66780e..1194fe79df 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": "693aa1f", - "sha256": "13ab69ab94e496e8254f01337eaa5ef9e2197fb0bf64f78100eaab66cb3c1eff" + "version": "5ae35e6", + "sha256": "cdc948ce65b3ed0befbbfab7c816f2db63ae9207bbd85653d3484516c7ac3238" } diff --git a/frontend/src/app.d.ts b/frontend/src/app.d.ts index 47aff3f3b3..2239c0e4fb 100644 --- a/frontend/src/app.d.ts +++ b/frontend/src/app.d.ts @@ -4,7 +4,7 @@ // for information about these interfaces declare namespace App { interface Stuff { - title: string? + title?: string } } diff --git a/frontend/src/lib/aiStore.test.ts b/frontend/src/lib/aiStore.test.ts index be8980e93a..22c841c91a 100644 --- a/frontend/src/lib/aiStore.test.ts +++ b/frontend/src/lib/aiStore.test.ts @@ -1,16 +1,53 @@ import { describe, expect, it, vi } from 'vitest' import { get } from 'svelte/store' -// aiStore pulls in the (heavy) copilot lib for workspaceAIClients and the gen -// client for WorkspaceService; neither is exercised by setCopilotInfo. +let requests: { workspace: string; resolve: (config: any) => void }[] = [] + +// aiStore pulls in the (heavy) copilot lib for workspaceAIClients; setCopilotInfo does not +// exercise it. vi.mock('./components/copilot/lib', () => ({ workspaceAIClients: { init: () => {} } })) vi.mock('./gen', () => ({ - WorkspaceService: { getCopilotInfo: async () => ({}) } + WorkspaceService: { + getCopilotInfo: ({ workspace }: { workspace: string }) => + new Promise((resolve) => requests.push({ workspace, resolve })) + } })) -import { isWebSearchEnabledForProvider, setCopilotInfo, copilotInfo } from './aiStore' +import { + isWebSearchEnabledForProvider, + setCopilotInfo, + copilotInfo, + getWorkspaceCopilotInfo, + invalidateWorkspaceCopilotInfo, + loadWorkspaceCopilotInfo +} from './aiStore' + +const withModel = (model: string) => ({ + providers: { anthropic: { resource_path: 'u/admin/anthropic', models: [model] } } +}) +const modelOf = (info: { aiModels: { model: string }[] } | undefined) => info?.aiModels[0]?.model + +// A config saved, or one every workspace inherits, while a session's load is in flight: the load +// read the config from before the save and must not keep it. +describe.each([ + ['its workspace', () => invalidateWorkspaceCopilotInfo('ws')], + ['every workspace', () => invalidateWorkspaceCopilotInfo()] +])('loadWorkspaceCopilotInfo invalidated for %s mid-fetch', (_, invalidate) => { + it('refetches instead of keeping the outdated config', async () => { + requests = [] + invalidateWorkspaceCopilotInfo() + const load = loadWorkspaceCopilotInfo('ws') + invalidate() + requests[0].resolve(withModel('before-save')) + await vi.waitFor(() => expect(requests).toHaveLength(2)) + requests[1].resolve(withModel('saved')) + + expect(modelOf(await load)).toBe('saved') + expect(modelOf(getWorkspaceCopilotInfo('ws'))).toBe('saved') + }) +}) describe('setCopilotInfo legacy /thinking migration', () => { it('strips the /thinking suffix from configured model slots', () => { diff --git a/frontend/src/lib/aiStore.ts b/frontend/src/lib/aiStore.ts index ac9320f8a3..246fd0a1f0 100644 --- a/frontend/src/lib/aiStore.ts +++ b/frontend/src/lib/aiStore.ts @@ -3,13 +3,15 @@ // import aiStore back, and such a cycle crashes the app once the bundler splits it across // chunks (docs/frontend-import-cycles.md; the build fails on the chunk cycle, not on this). import { writable, get } from 'svelte/store' +import { SvelteMap } from 'svelte/reactivity' import { type AIProviderModel, type AIProvider, type AIConfig, type AIWebSearchConfig, type FreeTierInfo, - type ModelPriceOverride + type ModelPriceOverride, + WorkspaceService } from './gen' import { aiUserDisabled, @@ -40,7 +42,7 @@ export const copilotSessionModel = writable<ReasoningProviderModel | undefined>( : undefined ) -export const copilotInfo = writable<{ +export type CopilotInfo = { enabled: boolean // The workspace hid the assistant (`ai_config.copilot_disabled`). `enabled` is then false // whatever the providers say, and the AI entry points that nudge "configure AI" when @@ -64,7 +66,9 @@ export const copilotInfo = writable<{ // Windmill's free tier. `exhausted` means the grant is spent: there is no model, but // that is a different state from "never configured" and the UI must say so. freeTier?: FreeTierInfo -}>({ +} + +export const copilotInfo = writable<CopilotInfo>({ enabled: false, workspaceDisabled: false, codeCompletionModel: undefined, @@ -78,13 +82,27 @@ export const copilotInfo = writable<{ webSearchEnabledProviders: {} }) +// Each workspace's AI config, read by AI sessions, which send with their own workspace's config +// rather than the tab's. Only `loadWorkspaceCopilotInfo` fills it: a save invalidates instead. +const workspaceCopilotInfos = new SvelteMap<string, CopilotInfo>() +const workspaceLoads = new Map<string, Promise<CopilotInfo>>() +// Bumped by invalidation: a load started before it refetches instead of keeping its answer. +let allWorkspacesVersion = 0 +const workspaceVersions = new Map<string, number>() +const versionOf = (workspace: string) => + `${allWorkspacesVersion}:${workspaceVersions.get(workspace) ?? 0}` + // Apply the per-user opt-out live: toggling it flips `enabled` without re-fetching. // Only enable when providers exist (aiModels is populated whenever the config has any). aiUserDisabled.subscribe((disabled) => { - copilotInfo.update((info) => ({ + const withOptOut = (info: CopilotInfo): CopilotInfo => ({ ...info, enabled: info.aiModels.length > 0 && !disabled && !info.workspaceDisabled - })) + }) + copilotInfo.update(withOptOut) + for (const [workspace, info] of workspaceCopilotInfos) { + workspaceCopilotInfos.set(workspace, withOptOut(info)) + } }) /** Strip the deprecated /thinking suffix from a configured model slot, if present. */ @@ -110,7 +128,7 @@ function dedupeModels(models: AIProviderModel[]): AIProviderModel[] { // workspace's provider/model while the scoped load is still in flight. export const copilotWorkspace = writable<string | undefined>(undefined) -export function setCopilotInfo(aiConfig: AIConfig) { +function buildCopilotInfo(aiConfig: AIConfig, userDisabled: boolean): CopilotInfo { if (Object.keys(aiConfig.providers ?? {}).length > 0) { const aiModels = dedupeModels( Object.entries(aiConfig.providers ?? {}).flatMap(([provider, providerConfig]) => @@ -128,20 +146,10 @@ export function setCopilotInfo(aiConfig: AIConfig) { ]) ) as Partial<Record<AIProvider, boolean>> - copilotSessionModel.update((model) => { - if ( - model && - !aiModels.some((m) => m.model === model.model && m.provider === model.provider) - ) { - return undefined - } - return model - }) - const workspaceDisabled = aiConfig.copilot_disabled === true - copilotInfo.set({ + return { // Providers are configured; only the workspace or per-user opt-outs can gate it off. - enabled: !workspaceDisabled && !get(aiUserDisabled), + enabled: !workspaceDisabled && !userDisabled, workspaceDisabled, // Strip the deprecated /thinking suffix from the configured model slots too, // otherwise a workspace whose default still carries it sends an invalid model id. @@ -156,11 +164,9 @@ export function setCopilotInfo(aiConfig: AIConfig) { webSearchBackend: aiConfig.web_search?.provider, modelPricing: aiConfig.model_pricing ?? {}, freeTier: aiConfig.free_tier - }) + } } else { - copilotSessionModel.set(undefined) - - copilotInfo.set({ + return { enabled: false, workspaceDisabled: aiConfig.copilot_disabled === true, codeCompletionModel: undefined, @@ -175,20 +181,26 @@ export function setCopilotInfo(aiConfig: AIConfig) { // An exhausted free grant lands here — no providers, but the reason AI is off // is "you used it up", not "you never set it up". freeTier: aiConfig.free_tier - }) + } } } -export function isWebSearchEnabledForProvider(provider: AIProvider | undefined): boolean { +export function isWebSearchEnabledForProvider( + provider: AIProvider | undefined, + info: CopilotInfo = get(copilotInfo) +): boolean { if (!provider) { return false } - return get(copilotInfo).webSearchEnabledProviders?.[provider] ?? true + return info.webSearchEnabledProviders?.[provider] ?? true } export function getCurrentModel(): ReasoningProviderModel { - const model = - get(copilotSessionModel) ?? get(copilotInfo).defaultModel ?? get(copilotInfo).aiModels[0] + return resolveModelFor(get(copilotInfo)) +} + +export function resolveModelFor(info: CopilotInfo): ReasoningProviderModel { + const model = tryResolveModelFor(info) if (!model) { throw new Error('No model selected') } @@ -196,7 +208,10 @@ export function getCurrentModel(): ReasoningProviderModel { } export function getMetadataModel(): AIProviderModel { - const info = get(copilotInfo) + return resolveMetadataModelFor(get(copilotInfo)) +} + +export function resolveMetadataModelFor(info: CopilotInfo): AIProviderModel { const model = info.metadataModel ?? info.defaultModel ?? info.aiModels[0] if (!model) { throw new Error('No model selected') @@ -205,9 +220,85 @@ export function getMetadataModel(): AIProviderModel { } export function tryGetCurrentModel(): ReasoningProviderModel | undefined { - return get(copilotSessionModel) ?? get(copilotInfo).defaultModel ?? get(copilotInfo).aiModels[0] + return tryResolveModelFor(get(copilotInfo)) } +/** `workspace`'s AI config if loaded; otherwise starts loading it and returns undefined. */ +export function getWorkspaceCopilotInfo(workspace: string): CopilotInfo | undefined { + const info = workspaceCopilotInfos.get(workspace) + if (!info) { + loadWorkspaceCopilotInfo(workspace).catch((e) => + console.error(`Failed to load the AI config of workspace ${workspace}`, e) + ) + } + return info +} + +/** `workspace`'s AI config for a request made on its behalf, without touching the tab's. + * Fetched once and kept until invalidated. `fresh` refetches a config that may have changed + * elsewhere: unlike after a save, the one held stays readable until the new one lands, so what + * shows it does not blank meanwhile, and a load already in flight is as fresh and is shared. */ +export function loadWorkspaceCopilotInfo(workspace: string, fresh = false): Promise<CopilotInfo> { + const known = workspaceCopilotInfos.get(workspace) + if (known && !fresh) return Promise.resolve(known) + let load = workspaceLoads.get(workspace) + if (!load) { + const version = versionOf(workspace) + load = WorkspaceService.getCopilotInfo({ workspace }) + // Settled before the retry below, which would otherwise be handed this same load. + .finally(() => workspaceLoads.delete(workspace)) + .then((config) => { + if (version !== versionOf(workspace)) return loadWorkspaceCopilotInfo(workspace) + const info = buildCopilotInfo(config, get(aiUserDisabled)) + workspaceCopilotInfos.set(workspace, info) + return info + }) + workspaceLoads.set(workspace, load) + } + return load +} + +/** After a save of `workspace`'s AI config, or with none of a config every workspace inherits + * (the instance's): the next request refetches. */ +export function invalidateWorkspaceCopilotInfo(workspace?: string) { + if (workspace) { + workspaceVersions.set(workspace, (workspaceVersions.get(workspace) ?? 0) + 1) + workspaceCopilotInfos.delete(workspace) + } else { + allWorkspacesVersion++ + workspaceCopilotInfos.clear() + } +} + +export function setCopilotInfo(aiConfig: AIConfig) { + applyCopilotInfo(buildCopilotInfo(aiConfig, get(aiUserDisabled))) +} + +export function applyCopilotInfo(info: CopilotInfo) { + copilotSessionModel.update((model) => (model && isOffered(info, model) ? model : undefined)) + copilotInfo.set(info) +} + +function isOffered(info: CopilotInfo, model: AIProviderModel): boolean { + return info.aiModels.some((m) => m.model === model.model && m.provider === model.provider) +} + +/** The model a request for `info`'s workspace sends: the shared pick when that workspace offers + * it, else its default, else its first model. Never one the workspace does not offer. */ +export function tryResolveModelFor(info: CopilotInfo): ReasoningProviderModel | undefined { + const picked = get(copilotSessionModel) + if (picked && isOffered(info, picked)) return picked + return info.defaultModel ?? info.aiModels[0] +} + +/** A workspace a request is made for and that workspace's AI config, kept together so a request + * never pairs one workspace's credentials with another's settings. */ +export type AiTarget = { workspace: string; info: CopilotInfo } + +/** What an AI session sends with, for code that otherwise reads the tab's model and config. + * Both are undefined while the session's config is loading. */ +export type SessionAi = { model: ReasoningProviderModel | undefined; info: CopilotInfo | undefined } + export function getUserCustomPrompts(): Record<string, string> { const stored = getLocalSetting(USER_CUSTOM_PROMPTS_KEY) if (stored) { @@ -242,8 +333,11 @@ export function getCombinedCustomPrompt(mode: string): string | undefined { // Like getCombinedCustomPrompt but keeps the workspace and user slices separate so the // Global system prompt can label them distinctly — only the user slice is editable by the // update_user_instructions tool. -export function getCustomPromptParts(mode: string): { workspace?: string; user?: string } { - const workspace = get(copilotInfo).customPrompts?.[mode]?.trim() || undefined +export function getCustomPromptParts( + mode: string, + customPrompts: Record<string, string> | undefined = get(copilotInfo).customPrompts +): { workspace?: string; user?: string } { + const workspace = customPrompts?.[mode]?.trim() || undefined const user = getUserCustomPrompts()[mode]?.trim() || undefined return { workspace, user } } diff --git a/frontend/src/lib/assets/app.css b/frontend/src/lib/assets/app.css index 8f19f626ca..f34427d7a7 100644 --- a/frontend/src/lib/assets/app.css +++ b/frontend/src/lib/assets/app.css @@ -62,6 +62,16 @@ font-weight: 100 900; font-display: swap; } + /* Without it the browser fakes italic by slanting the roman. Fetched only once a page sets + italic text. Public apps load this file on the public app domain, which serves only the + paths `public_app_layer.rs` lists: a font added here is added there too. */ + @font-face { + font-family: 'Inter'; + font-style: italic; + src: url('/Inter-Variable-Italic.woff2') format('woff2'); + font-weight: 100 900; + font-display: swap; + } /* Firefox rasterizes the macOS bitmap emoji font (Apple Color Emoji, sbix) at a size that ignores an ancestor's `transform: scale()`, so emoji keep their unzoomed size @@ -329,6 +339,32 @@ transition: none !important; } +/* Draggable gutter between a session's chat and its preview: a real (layout-occupying) + 10px-wide grab zone, no overlap tricks that could cover the chat's scrollbar + or the preview's edge. Transparent at rest; on hover the app-global + `.splitpanes__splitter::after` grabber fades in. Uses a dedicated class, not + the shared `.splitter-hidden`, which force-zeroes splitter opacity and would + hide that grabber. */ +.splitpanes--vertical.session-splitter > .splitpanes__splitter { + background-color: transparent !important; + border: none !important; + width: 10px !important; +} +/* Inset the global hover grabber from the pane's top/bottom edges so the line + doesn't run the full height, and round its ends into a pill. */ +.splitpanes--vertical.session-splitter > .splitpanes__splitter::after { + top: 8px !important; + bottom: 8px !important; + height: auto !important; + border-radius: 9999px !important; +} +/* Collapsed preview: the pane is resized to 0 but stays mounted, so remove + the gutter entirely — it would otherwise leave a dead 10px drag zone on the + chat's right edge. */ +.splitpanes--vertical.splitter-off > .splitpanes__splitter { + display: none !important; +} + .monaco-workbench > .notifications-toasts.visible { display: none !important; } @@ -458,8 +494,11 @@ input[type='time']::-webkit-calendar-picker-indicator { opacity: 1; } } +/* No fill: a filled animation never ends for the compositor, so every faded element (Home's whole + scroll container among them) keeps a GPU layer for the page's lifetime. `from` paints on the + first frame anyway, and `to` is the resting style. */ .wm-page-in { - animation: wm-page-in 500ms ease-out both; + animation: wm-page-in 500ms ease-out; } @media (prefers-reduced-motion: reduce) { .wm-page-in { diff --git a/frontend/src/lib/components/AIProviderPicker.svelte b/frontend/src/lib/components/AIProviderPicker.svelte index 0d23ab55a3..9997ea8274 100644 --- a/frontend/src/lib/components/AIProviderPicker.svelte +++ b/frontend/src/lib/components/AIProviderPicker.svelte @@ -7,9 +7,14 @@ DECISION_AI_PROVIDERS, aiProviderDetails } from './copilot/lib' - import type { AIProvider, ProviderConfig } from '$lib/gen' + import { + ResourceService, + VariableService, + type AIProvider, + type ProviderConfig + } from '$lib/gen' import ResourcePicker from './ResourcePicker.svelte' - import { aiResourceProvider } from './copilot/aiResourceProvider' + import { aiResourceProvider, vertexPublisherProvider } from './copilot/aiResourceProvider' import Toggle from './Toggle.svelte' import { saveConfig, removeConfig, isSameAsStoredConfig } from './aiProviderStorage' import AIReasoningEffortPicker from './AIReasoningEffortPicker.svelte' @@ -58,10 +63,14 @@ const offeredProviders = Object.keys( untrack(() => decision) ? DECISION_AI_PROVIDERS : AI_PROVIDERS ) - // Federated Anthropic resources authenticate the anthropic provider without a key of their own. + // Federated resources authenticate a provider without a key of their own. const providerResourceTypes = [ ...offeredProviders, - ...(offeredProviders.includes('anthropic') ? ['anthropic_federated'] : []) + ...(offeredProviders.includes('anthropic') ? ['anthropic_federated'] : []), + // Gemini decisions are served by the Gemini API only, never by Vertex. + ...(offeredProviders.includes('googleai') && !untrack(() => decision) + ? ['vertex_ai_federated'] + : []) ].join(',') if (!_uncheckedValue) { @@ -140,15 +149,46 @@ } } + let latestPick = 0 + + /** The provider a Vertex federated resource serves, Claude or Gemini depending on its base + * URL, which can be a variable. When the URL names no publisher, a Vertex provider already + * chosen is kept rather than guessed over. */ + async function vertexResourceProvider(path: string): Promise<AIProvider> { + const workspace = effectiveWorkspace + let baseUrl = await ResourceService.getResourceValue({ workspace, path }) + .then((v) => (v as Record<string, any> | undefined)?.base_url) + .catch(() => undefined) + if (typeof baseUrl === 'string' && baseUrl.startsWith('$var:')) { + baseUrl = await VariableService.getVariableValue({ + workspace, + path: baseUrl.substring('$var:'.length) + }).catch(() => undefined) + } + const current = value?.kind + return ( + vertexPublisherProvider(baseUrl) ?? + (current === 'anthropic' || current === 'googleai' ? current : 'googleai') + ) + } + /** * The provider kind follows the resource that was picked. Driven by the pick rather than by an * effect on the picker's `valueType`, which also resolves for the value the field was opened on * and would rewrite a saved config just for being looked at. */ - function onResourcePicked(_path: string | undefined, type: string | undefined) { + async function onResourcePicked(path: string | undefined, type: string | undefined) { + const pick = ++latestPick // An empty type is the placeholder the picker keeps for a saved path it could not find. It // says nothing about the provider, so the kind stands. - const provider = aiResourceProvider(type) + const provider = + type === 'vertex_ai_federated' && path + ? await vertexResourceProvider(path) + : aiResourceProvider(type) + // A later pick owns the kind. + if (pick !== latestPick) { + return + } if (!value || !provider || !offeredProviders.includes(provider)) { return } diff --git a/frontend/src/lib/components/AIReasoningEffortPicker.svelte b/frontend/src/lib/components/AIReasoningEffortPicker.svelte index 39b4e80011..a05b1e6ba6 100644 --- a/frontend/src/lib/components/AIReasoningEffortPicker.svelte +++ b/frontend/src/lib/components/AIReasoningEffortPicker.svelte @@ -1,8 +1,5 @@ <script lang="ts"> - import { Brain, ChevronDown } from 'lucide-svelte' - import DropdownV2 from './DropdownV2.svelte' - import Button from './common/button/Button.svelte' - import type { Item } from '$lib/utils' + import Select from './select/Select.svelte' import type { AIProvider } from '$lib/gen' import { getReasoningCapability, explicitOffToken } from './copilot/reasoningRegistry' @@ -40,28 +37,17 @@ // reason by default keep a distinct "Model default" plus an explicit off. let offViaOmission = $derived(capability.canDisable && offToken === undefined) - // Label shown on the trigger for the current selection. - let currentLabel = $derived( - !value ? (offViaOmission ? 'off' : 'Model default') : value === offToken ? 'off' : value - ) + // Select cannot show an item for an undefined value, so the unset effort is + // carried by this sentinel and mapped back to undefined on write. + const UNSET = '__model_default__' - let items = $derived.by((): Item[] => { - const opts: Item[] = [ - { - displayName: offViaOmission ? 'off' : 'Model default', - selected: !value, - action: () => (value = undefined) - } - ] + let items = $derived.by(() => { + const opts = [{ label: offViaOmission ? 'off' : 'Model default', value: UNSET }] if (capability.canDisable && offToken !== undefined) { - opts.push({ - displayName: 'off', - selected: value === offToken, - action: () => (value = offToken) - }) + opts.push({ label: 'off', value: offToken }) } for (const level of capability.levels) { - opts.push({ displayName: level, selected: value === level, action: () => (value = level) }) + opts.push({ label: level, value: level }) } return opts }) @@ -87,20 +73,10 @@ {:else if !capability.supported} <div class="text-xs text-tertiary">The selected model does not support reasoning effort.</div> {:else} - <DropdownV2 {items} {disabled} placement="bottom-start" fixedHeight={false} class="justify-start"> - {#snippet buttonReplacement()} - <Button - nonCaptureEvent - {disabled} - unifiedSize="xs" - variant="default" - startIcon={{ icon: Brain }} - endIcon={{ icon: ChevronDown }} - btnClasses="w-full justify-between font-normal text-secondary" - title="Reasoning effort" - > - <span class="truncate">{currentLabel}</span> - </Button> - {/snippet} - </DropdownV2> + <Select + {items} + bind:value={() => value ?? UNSET, (v) => (value = !v || v === UNSET ? undefined : v)} + {disabled} + clearable={false} + /> {/if} diff --git a/frontend/src/lib/components/AccessDrawer.svelte b/frontend/src/lib/components/AccessDrawer.svelte index 7031280d1a..b51786bbcd 100644 --- a/frontend/src/lib/components/AccessDrawer.svelte +++ b/frontend/src/lib/components/AccessDrawer.svelte @@ -34,6 +34,7 @@ ExternalLink, Folder, FolderTree, + Loader2, Lock, Plus, User, @@ -59,8 +60,12 @@ let openState: Record<string, boolean> = $state({}) let expandAll: boolean | undefined = $state() let grantOpen = $state(false) + let navigator: GrantNavigator | undefined = $state() /** The row menu that is open, as `kind:path`. */ let openMenu: string | undefined = $state() + /** The row whose grant is being written, as `kind:path`. Its menu would otherwise send the + * same change again before the tree reloads with the new level. */ + let changing: string | undefined = $state() let grantPopover: Popover | undefined = $state() let grantAnchor: HTMLElement | undefined = $state() let needsOf: { kind: RunnableKind; path: string } | undefined = $state() @@ -136,6 +141,8 @@ } async function changeGrant(kind: string, path: string, level: GrantLevel) { + if (changing) return + changing = `${kind}:${path}` try { await setGrant($operatingWorkspace!, kind, path, principal, level) } catch (e) { @@ -143,6 +150,7 @@ sendUserToast(`Could not change access to ${what}: ${e?.body ?? e}`, true) } await reload() + changing = undefined } /** `current` is the grant's level: `true` for write, `false` for read. */ @@ -234,13 +242,29 @@ return `${principal} is a member of ${node.key}, so ${principal} can write every item under ${node.key}/, including items added later.` } - /** Grants on the item itself. What its folder or space gives is said once, on that row. */ + /** Grants on the item itself, which decide whether its level reads as its own. */ function itemGrants(item: AccessItem): string[] { return item.reasons.flatMap((r) => r.type === 'user' ? ['Shared directly'] : r.type === 'group' ? [viaLabel(`g/${r.group}`)] : [] ) } + /** Every reason the item is held: its own grants, then its folder or space. */ + function itemReasons(item: AccessItem): string[] { + const labels = item.reasons.map((r) => + r.type === 'user' + ? 'Shared directly' + : r.type === 'group' + ? viaLabel(`g/${r.group}`) + : r.type === 'folder' + ? `Through f/${r.folder}` + : r.type === 'group_path' + ? `Through g/${r.group}` + : 'Own path' + ) + return [...new Set(labels)] + } + function levelClass(item: AccessItem, grants: string[], owner: AccessOwnerNode): string { if (!grants.length) return 'text-hint' return item.write && owner.whole && !owner.write ? 'font-semibold text-emphasis' : '' @@ -282,9 +306,14 @@ <Lock size={14} class="text-secondary" aria-label={blocked} /> {#snippet text()}{blocked}{/snippet} </Tooltip> + {:else if changing === `${kind}:${path}`} + <span class="flex size-5 items-center justify-center -my-0.5" role="status" aria-label="Saving"> + <Loader2 size={14} class="animate-spin text-secondary" /> + </span> {:else} {@const key = `${kind}:${path}`} <DropdownV2 + disabled={!!changing} size="xs" fixedHeight={false} class="-my-0.5" @@ -302,12 +331,13 @@ <!-- The drawer answers Escape on window too, and `preventEscape` is read after a popover or menu has already closed, so with the Grant popover or a row menu open its Escape is taken here - before either sees it. --> + before either sees it. The navigator's own dialog or row dropdown closes first. --> <svelte:window onkeydowncapture={(e) => { if (e.key !== 'Escape' || (!grantOpen && !openMenu)) return e.stopPropagation() e.preventDefault() + if (grantOpen && navigator?.escape(e.target)) return grantOpen = false openMenu = undefined }} @@ -374,13 +404,7 @@ {/snippet} {#snippet content()} {#if access} - <GrantNavigator - {principal} - {access} - onGranted={reload} - onFindReads={findReads} - /> - {/if} + <GrantNavigator bind:this={navigator} {principal} {access} onChange={reload} /> {/if} {/snippet} </Popover> </div> @@ -553,7 +577,7 @@ >{item.write ? 'Write' : 'Read'}</span > </Cell> - <Cell>{grants.join(', ')}</Cell> + <Cell>{itemReasons(item).join(', ')}</Cell> <Cell last actions> {@const own = ownItemGrant(item)} {#if own !== undefined} diff --git a/frontend/src/lib/components/AgentStreamDisplay.svelte b/frontend/src/lib/components/AgentStreamDisplay.svelte index cf1646a614..b28e739e6d 100644 --- a/frontend/src/lib/components/AgentStreamDisplay.svelte +++ b/frontend/src/lib/components/AgentStreamDisplay.svelte @@ -1,6 +1,8 @@ <script lang="ts"> - import { untrack } from 'svelte' - import ChatCollapsibleCard from './copilot/chat/ChatCollapsibleCard.svelte' + import { onDestroy, untrack } from 'svelte' + import AgentTrace from './AgentTrace.svelte' + import type { AgentTraceEntry } from './agentTrace' + import { prefersInstantReveal, TypewriterReveal } from './copilot/chat/typewriterReveal' import GfmMarkdown from './GfmMarkdown.svelte' import { runPane } from './agentScroll' import { createBottomSticker } from './stickToBottom' @@ -30,6 +32,12 @@ const continues = progress.key === streamKey && raw.length >= progress.consumed const base = continues ? progress : emptyAgentStreamProgress() progress = { ...advanceAgentStream(raw, base), key: streamKey } + if (!continues) { + currentLane.restart() + reasoningLane.restart() + } + currentLane.feed(progress.stream.current) + reasoningLane.feed(progress.stream.reasoning) if (!continues) { // Another run, so the reader's decision to stop following the previous // one does not carry over: this one starts at its latest output. @@ -38,7 +46,68 @@ }) }) - let stream = $derived(progress.stream) + // The buffer lands in bursts, once per poll of the job, so the live text is shown as a + // prefix a typewriter advances, as the chat does for its own replies. Finished entries + // are shown whole: a tool call settles that text, and pacing it under the card would + // reorder the trace. + function revealLane() { + let revealed = $state(0) + let fed = '' + const reveal = new TypewriterReveal({ + instant: prefersInstantReveal(), + // The chat's run card polls once a second; a shorter lag types out each burst + // and then stalls until the next. + smoothingMs: 1000, + onReveal: (chunk) => (revealed += chunk.length) + }) + function restart() { + reveal.reset() + revealed = 0 + fed = '' + } + return { + get revealed() { + return revealed + }, + feed(text: string) { + // The text only grows within a turn; anything else is the next turn's. + if (!text.startsWith(fed)) { + restart() + } + reveal.push(text.slice(fed.length)) + fed = text + }, + restart, + reset: () => reveal.reset() + } + } + const currentLane = revealLane() + const reasoningLane = revealLane() + onDestroy(() => { + currentLane.reset() + reasoningLane.reset() + }) + + let stream = $derived({ + entries: progress.stream.entries, + current: progress.stream.current.slice(0, currentLane.revealed), + reasoning: progress.stream.reasoning.slice(0, reasoningLane.revealed) + }) + + const traceEntries: AgentTraceEntry[] = $derived( + progress.stream.entries.map((entry) => + entry.kind === 'tool' + ? { + kind: 'tool', + name: entry.name, + args: entry.args, + result: entry.result, + running: entry.running, + failed: entry.success === false + } + : entry + ) + ) let anchor: HTMLElement | undefined = $state() // Carry the reader along as the text is written, unless they have scrolled up @@ -54,10 +123,18 @@ if (!pane) { return } + // Told apart by direction, not by `isOwnScroll`'s time window: the typewriter scrolls + // every frame, so every reader scroll would land inside that window and be undone. + // The end is checked first: content shrinking (reasoning replaced by the answer or a + // tool row) also moves the pane up, but leaves it clamped at the end. + let lastTop = pane.scrollTop const onScroll = () => { - if (!sticker.isOwnScroll()) { - following = sticker.isAtEnd(pane) + if (sticker.isAtEnd(pane)) { + following = true + } else if (pane.scrollTop < lastTop) { + following = false } + lastTop = pane.scrollTop } pane.addEventListener('scroll', onScroll, { passive: true }) return () => pane.removeEventListener('scroll', onScroll) @@ -78,22 +155,13 @@ the live text into a row. The text at the bottom is deliberately unlabelled — a turn that goes on to call a tool was narration, and the run's end settles which. --> <div bind:this={anchor} class="flex flex-col w-full py-3 gap-1"> - {#each stream.entries as entry, index (entry.kind === 'tool' ? entry.callId : index)} - {#if entry.kind === 'tool'} - <ChatCollapsibleCard - label={entry.name} - expanded={false} - toggleable={false} - shimmer={entry.running} - onToggle={() => {}} - labelClass={entry.success === false ? 'text-red-500' : ''} - /> - {:else} - <div> - <GfmMarkdown md={entry.content} noPadding /> - </div> - {/if} - {/each} + {#if traceEntries.length > 0} + <!-- The finished result's renderer, so a row reads the same while the run streams. + The landed result mounts its own trace: rows opened here close then, and a + failed call's label is red only here, since the finished trace has no outcome + for a row until its job is loaded. --> + <AgentTrace entries={traceEntries} runKey={streamKey ?? ''} /> + {/if} {#if stream.current !== ''} <div> diff --git a/frontend/src/lib/components/AgentTrace.svelte b/frontend/src/lib/components/AgentTrace.svelte index 3d671f46c8..0aa8b5e0dd 100644 --- a/frontend/src/lib/components/AgentTrace.svelte +++ b/frontend/src/lib/components/AgentTrace.svelte @@ -16,9 +16,12 @@ interface Props { entries: AgentTraceEntry[] workspaceId?: string + /** Identifies the run. Without it a new `entries` counts as another run, which is + * wrong for a streamed trace: it gets new entries on every poll. */ + runKey?: string } - let { entries, workspaceId }: Props = $props() + let { entries, workspaceId, runKey }: Props = $props() let expanded = new SvelteSet<number>() // A search opens on its sources, so for it the reader's toggle records a close. @@ -26,7 +29,7 @@ // Row state is keyed by position, which means nothing once the viewer is handed // another run: row 0 would stay open showing the previous run's job. $effect(() => { - entries + runKey ?? entries expanded.clear() collapsedSearches.clear() jobs.clear() @@ -109,12 +112,14 @@ </ChatCollapsibleCard> {:else} {@const job = jobOf(entry.jobId)} - {@const failed = job?.type === 'CompletedJob' && !job.success} + {@const failed = entry.failed || (job?.type === 'CompletedJob' && !job.success)} {@const search = webSearchResultOf(entry.result)} <ChatCollapsibleCard label={toolLabel(entry, search)} expanded={expanded.has(index)} onToggle={() => toggle(index, entry)} + shimmer={entry.running} + labelClass={entry.failed ? 'text-red-500' : ''} contentClass="space-y-3" > {#if entry.args} @@ -130,6 +135,7 @@ title="Result" content={entry.result} error={failed ? entry.result : undefined} + loading={entry.running} /> {/if} {#if entry.resourcePath} diff --git a/frontend/src/lib/components/ApiConnectForm.svelte b/frontend/src/lib/components/ApiConnectForm.svelte index 5771e73910..dc5a5436a1 100644 --- a/frontend/src/lib/components/ApiConnectForm.svelte +++ b/frontend/src/lib/components/ApiConnectForm.svelte @@ -60,7 +60,7 @@ onSynced = undefined }: Props = $props() - let aiProvider = $derived(aiResourceProvider(resourceType)) + let aiProvider = $derived(aiResourceProvider(resourceType, args)) let schema = $state(emptySchema()) let notFound = $state(false) diff --git a/frontend/src/lib/components/AppConnectInner.svelte b/frontend/src/lib/components/AppConnectInner.svelte index 069965b4e7..b584815a7f 100644 --- a/frontend/src/lib/components/AppConnectInner.svelte +++ b/frontend/src/lib/components/AppConnectInner.svelte @@ -54,7 +54,7 @@ import SchemaForm from './SchemaForm.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import type { NativeConnect } from './triggers/native/utils' - import { AI_RESOURCE_TYPE_ALTERNATIVES } from './copilot/aiResourceProvider' + import { aiResourceTypeAlternative } from './copilot/aiResourceProvider' const operatingWorkspace = useOperatingWorkspace() @@ -219,6 +219,7 @@ : undefined ) let defaultName = $derived(tokenKind ? `${resourceType}_${tokenKind}` : resourceType) + let providerName = $derived(resourceTypeDisplayName(resourceType)) /** Last description filled in from `tokenKind`, replaced on reconnect unless the user edited it. */ let generatedDescription = '' @@ -259,14 +260,21 @@ return registryEntryFor(connectClient, resourceType) } - let resourceTypeAlternative = $derived(AI_RESOURCE_TYPE_ALTERNATIVES[resourceType]) + let resourceTypeAlternative = $derived(aiResourceTypeAlternative(resourceType, args)) - function switchToResourceType(rt: string) { + async function switchToResourceType(rt: string, carry: string[] = []) { + const carried = Object.fromEntries( + carry.filter((key) => args?.[key] !== undefined).map((key) => [key, args[key]]) + ) connectClient = rt resourceType = rt linkedSecrets = [] args = {} - getResourceTypeInfo() + await getResourceTypeInfo() + // The form remounts on the new type's schema and starts from empty arguments, so the + // fields worth keeping go in after it has. + await tick() + args = { ...args, ...carried } } /** The static registry declares this provider supports client credentials */ @@ -1485,12 +1493,16 @@ onclick={() => enableClientCredentials()} class="text-xs font-normal text-accent w-fit -mt-4" > - Acquire the token automatically via client credentials instead + Connect as an app with a client ID and secret instead </button> {/if} {#if resourceTypeAlternative} <button - onclick={() => switchToResourceType(resourceTypeAlternative.resourceType)} + onclick={() => + switchToResourceType( + resourceTypeAlternative.resourceType, + resourceTypeAlternative.carry + )} class="text-xs font-normal text-accent w-fit -mt-4" > {resourceTypeAlternative.label} @@ -1531,16 +1543,11 @@ >Create a resource backed by an OAuth connection, whose token is fetched from the external services and refreshed automatically if needed before expiration.</div > - {#if ccBringYourOwn} - <button - onclick={() => { - manual = true - useClientCredentials = false - }} - class="text-xs font-normal text-accent w-fit mt-2" - > - Create resource manually instead - </button> + <!-- With client credentials, the Authentication section says whose identity applies. --> + {#if !supportsClientCredentials && !registryEntry()?.user_scopes} + <div class="text-xs text-secondary font-normal mt-1"> + The connection acts as you, with your {providerName} account's access. + </div> {/if} </div> @@ -1560,11 +1567,11 @@ {#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. + {providerName} connects as the app your admin set up for this instance, not as you. + No input needed. {:else} - {resourceType} connects server-to-server with the client credentials grant. Enter a - client ID and secret. + {providerName} connects as an app, not as you. Enter the client ID and secret of an + app registered in {providerName}. {/if} </div> {:else} @@ -1576,30 +1583,46 @@ aria-label="How to authenticate" > <RadioCard - label={`Sign in through ${resourceType}`} + label={`Log in with your ${providerName} account`} 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.'} + ? `Needs an OAuth client for ${providerName} in the instance settings, added by a superadmin.` + : 'Opens a browser window to authorize. The connection acts as you.'} selected={!useClientCredentials} onSelect={selectAuthCodeGrant} disabled={signInNeedsInstanceClient} - badge={signInNeedsInstanceClient ? setupNeededBadge : undefined} + badge={authCodeBadge} /> - {#snippet setupNeededBadge()} - <Badge verySmall class="px-2">Instance setup needed</Badge> + {#snippet authCodeBadge()} + <span class="text-2xs text-secondary font-normal">Authorization code</span> + {#if signInNeedsInstanceClient} + <Badge verySmall class="px-2">Instance setup needed</Badge> + {/if} {/snippet} <RadioCard label={useSharedInstanceCreds - ? 'Use the configured instance credentials' - : 'Use a client ID and secret'} + ? "Connect as this instance's app" + : 'Connect as an app'} description={useSharedInstanceCreds - ? "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.'} + ? 'Uses the app your admin set up. No input needed. The connection acts as that app, not as you.' + : `Enter the client ID and secret of an app registered in ${providerName}. The connection acts as that app, not as you.`} selected={useClientCredentials} onSelect={() => enableClientCredentials()} + badge={clientCredentialsBadge} /> + {#snippet clientCredentialsBadge()} + <span class="text-2xs text-secondary font-normal">Client credentials</span> + {/snippet} </div> {/if} + <button + onclick={() => { + manual = true + useClientCredentials = false + }} + class="text-xs font-normal text-accent w-fit mb-2" + > + Create resource manually instead + </button> {#if useClientCredentials && !useSharedInstanceCreds} <form class="flex flex-col gap-6"> diff --git a/frontend/src/lib/components/ArgInput.svelte b/frontend/src/lib/components/ArgInput.svelte index bfc3c81cc0..3abe981f72 100644 --- a/frontend/src/lib/components/ArgInput.svelte +++ b/frontend/src/lib/components/ArgInput.svelte @@ -98,6 +98,12 @@ customErrorMessage?: string | undefined onlyMaskPassword?: boolean nullable?: boolean + /** + * Write null into an untouched nullable string/list field. Only for forms whose value is + * submitted as run args: elsewhere an undefined value has its own meaning (an unset schema + * default, a step input still following its expression) that a written null would override. + */ + fillNullableDefault?: boolean title?: string | undefined placeholder?: string | undefined order?: string[] | undefined @@ -171,6 +177,7 @@ customErrorMessage = undefined, onlyMaskPassword = false, nullable = false, + fillNullableDefault = false, title = $bindable(undefined), placeholder = $bindable(undefined), order = $bindable(undefined), @@ -301,8 +308,19 @@ } } + // A nullable field's default is a real null: left undefined, the key is dropped + // from the submitted args and the runnable never receives it. + const unsetNullable = + fillNullableDefault && + nnullable && + value === undefined && + !ignoreValueUndefined && + (inputCat === 'string' || inputCat === 'list') if (nnullable && type === 'string' && value === '' && nvalue == null) { value = null + } else if (unsetNullable && nvalue == null) { + value = null + lastValue = value } else if (nvalue != null && !deepEqual(nvalue, value)) { value = nvalue lastValue = value @@ -867,6 +885,7 @@ <div class="px-4 pt-4 border rounded-md w-full"> <SchemaForm lightHeaderFont + {fillNullableDefault} {onlyMaskPassword} {disablePortal} {disabled} @@ -1010,6 +1029,7 @@ <div class="p-8 border rounded-md w-full"> <SchemaForm lightHeaderFont + {fillNullableDefault} {onlyMaskPassword} {disablePortal} {disabled} @@ -1190,6 +1210,7 @@ {#if orderEditable} <SchemaFormDnd lightHeaderFont + {fillNullableDefault} {nestedClasses} {onlyMaskPassword} {disablePortal} @@ -1226,6 +1247,7 @@ {:else} <SchemaForm lightHeaderFont + {fillNullableDefault} {nestedClasses} {onlyMaskPassword} {disablePortal} @@ -1314,6 +1336,7 @@ {#if orderEditable} <SchemaFormDnd lightHeaderFont + {fillNullableDefault} {nestedClasses} {onlyMaskPassword} {disablePortal} @@ -1346,6 +1369,7 @@ {:else} <SchemaForm lightHeaderFont + {fillNullableDefault} {nestedClasses} {onlyMaskPassword} {disablePortal} diff --git a/frontend/src/lib/components/AssignableTagsInner.svelte b/frontend/src/lib/components/AssignableTagsInner.svelte index fd5859b784..3da1163158 100644 --- a/frontend/src/lib/components/AssignableTagsInner.svelte +++ b/frontend/src/lib/components/AssignableTagsInner.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import { preventDefault, stopPropagation } from 'svelte/legacy' import { Button } from './common' @@ -169,7 +170,7 @@ } </script> -<svelte:window onkeydown={onKeyDown} /> +<HostWindow onkeydown={onKeyDown} /> {#snippet reachesAnyTagWarning(scoped: boolean)} Nothing fixed at its start or its end, so it allows anyone{scoped ? ' in its workspaces' : ''} to reach diff --git a/frontend/src/lib/components/AuthSettings.svelte b/frontend/src/lib/components/AuthSettings.svelte index de603f2047..8265e5d51f 100644 --- a/frontend/src/lib/components/AuthSettings.svelte +++ b/frontend/src/lib/components/AuthSettings.svelte @@ -19,17 +19,18 @@ import { capitalize, type Item } from '$lib/utils' import ClipboardPanel from './details/ClipboardPanel.svelte' import Toggle from './Toggle.svelte' - import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' - import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' import DropdownV2 from './DropdownV2.svelte' import { APP_TO_ICON_COMPONENT } from './icons' - import { ExternalLink, Plus, Circle, X } from 'lucide-svelte' + import { Check, ExternalLink, Plus, Circle, X } from 'lucide-svelte' import AzureOauthSettings from './AzureOauthSettings.svelte' - import Tooltip from './Tooltip.svelte' import { tick } from 'svelte' import { Popover } from './meltComponents' import SettingsPageHeader from './settings/SettingsPageHeader.svelte' import oauthConnectRegistry from '$oauth_connect_registry' + import { hasExplicitUrls, normalizeInstanceInput, templatedConnectConfig } from './oauthRegistry' + import { OauthService } from '$lib/gen' + import { resourceTypeDisplayName } from './resourceTypeDisplay' + import { sendUserToast } from '$lib/toast' interface Props { // Per-instance OAuth providers (Snowflake, ServiceNow, …): instance name @@ -37,6 +38,8 @@ // Required (and always bound by InstanceSettings) so it is never undefined. instanceInputs: Record<string, string> oauths?: Record<string, any> + /** The OAuth settings as last saved, to tell what an unsaved edit changes. */ + savedOauths?: Record<string, any> requirePreexistingUserForOauth?: boolean baseUrl?: string scim?: import('svelte').Snippet @@ -47,6 +50,7 @@ let { instanceInputs = $bindable(), oauths = $bindable(), + savedOauths = {}, requirePreexistingUserForOauth = $bindable(), baseUrl, scim, @@ -161,24 +165,63 @@ return registryCcCapable(name) && !registryAuthCodeCapable(name) } - /** Map the entry's grant_types to the single-select choice (so the segmented - * control always has exactly one selected and can never be empty) */ - function grantChoice(name: string): string { - const gts = oauths?.[name]?.['grant_types'] ?? ['authorization_code'] - const cc = gts.includes('client_credentials') - const ac = gts.includes('authorization_code') - if (cc && ac) return 'both' - if (cc) return 'client_credentials' - return 'authorization_code' + function grants(name: string): string[] { + return oauths?.[name]?.['grant_types'] ?? ['authorization_code'] } - /** Set the grant types from the segmented choice. The instance credentials are - * then used for every selected grant — authorization-code popup and/or - * server-to-server. */ - function setGrantChoice(name: string, choice: string) { - if (!oauths || !oauths[name]) return - oauths[name]['grant_types'] = - choice === 'both' ? ['authorization_code', 'client_credentials'] : [choice] + function setGrant(name: string, grant: string, on: boolean) { + if (!oauths?.[name]) return + oauths[name]['grant_types'] = [ + ...grants(name).filter((g) => g !== grant), + ...(on ? [grant] : []) + ] + } + + /** Client-credentials connections use this entry's id and secret. An entry saved + * before `share_client_credentials` existed shares through its grant alone. */ + function sharesCc(name: string, entries = oauths): boolean { + const entry = entries?.[name] + return ( + !!entry && + (entry['grant_types'] ?? ['authorization_code']).includes('client_credentials') && + entry['share_client_credentials'] !== false + ) + } + + /** A built-in provider offers bring-your-own client credentials from the registry + * alone, so its entry carries the grant only to share. A custom provider keeps the + * grant when sharing stops: it is what lets users bring their own. */ + function setSharesCc(name: string, on: boolean, custom: boolean) { + if (!oauths?.[name]) return + if (on || !custom) setGrant(name, 'client_credentials', on) + oauths[name]['share_client_credentials'] = on + } + + /** Custom providers only: users connect with their own client ID and secret. */ + function setServerToServer(name: string, on: boolean) { + if (!oauths?.[name]) return + setGrant(name, 'client_credentials', on) + oauths[name]['share_client_credentials'] = false + } + + let testingCc: Record<string, boolean> = $state({}) + + /** Run the client-credentials exchange with the entry as it stands, saved or not. */ + async function testClientCredentials(name: string) { + const tmpl = connectConfigTemplates[name] + const entry = { ...$state.snapshot(oauths?.[name]) } + const instance = tmpl ? normalizeInstanceInput(tmpl, instanceInputs[name] ?? '') : '' + if (tmpl && !hasExplicitUrls(tmpl, instance, entry.connect_config)) { + entry.connect_config = templatedConnectConfig(tmpl, instance) + } + testingCc[name] = true + try { + sendUserToast(await OauthService.testOauthClientCredentials({ requestBody: { name, entry } })) + } catch (e) { + sendUserToast(e?.body ?? e?.message ?? String(e), true) + } finally { + testingCc[name] = false + } } let showCustomOAuthForm = $state(false) @@ -197,7 +240,10 @@ newOauths[name] = { id: '', secret: '', - grant_types: registryCcOnly(name) ? ['client_credentials'] : ['authorization_code'] + // A built-in client-credentials-only entry exists only to offer one-click connections. + ...(registryCcOnly(name) + ? { grant_types: ['client_credentials'], share_client_credentials: true } + : { grant_types: ['authorization_code'] }) } oauths = newOauths dropdownOpen = false @@ -347,6 +393,16 @@ } </script> +<!-- A way the entry cannot go without: shown as set rather than as a switch. --> +{#snippet fixedWay(label: string, description: string)} + <div class="flex flex-col gap-1"> + <div class="flex items-center gap-2 text-xs text-primary"> + <Check size={14} class="text-green-500 shrink-0" />{label} + </div> + <span class="text-2xs text-secondary">{description}</span> + </div> +{/snippet} + {#if !hideTabs} <div> <Tabs bind:selected={tab} class="mb-4"> @@ -505,6 +561,16 @@ {@const headerLabel = k.endsWith('_sandbox') ? `${k.slice(0, -'_sandbox'.length)} (sandbox)` : k} + {@const custom = !windmillBuiltins.includes(k)} + {@const providerName = resourceTypeDisplayName(k)} + {@const authCode = grants(k).includes('authorization_code')} + {@const shared = sharesCc(k)} + {@const ownCc = custom && grants(k).includes('client_credentials')} + {@const single = !custom && (!registryCcCapable(k) || registryCcOnly(k))} + {@const credsSet = !!(oauths[k]['id'] && oauths[k]['secret'])} + {@const ccDesc = custom + ? 'Users connect as this app without entering anything or seeing its secret.' + : 'Users connect as this app without entering anything or seeing its secret. Users can still connect with their own client credentials.'} <div class="flex flex-col gap-2 pb-6"> <div class="flex flex-row items-center gap-2"> <IconComponent size={24} width="24" height="24" class="shrink-0" /> @@ -526,109 +592,175 @@ /> </div> <div class="p-4 border rounded-md flex flex-col gap-6"> - <label> - <span class="text-primary font-semibold text-xs">Client Id</span> - <input type="text" placeholder="Client Id" bind:value={oauths[k]['id']} /> - </label> - <label for="{k}_client_secret_oauth"> - <span class="text-primary font-semibold text-xs">Client Secret</span> - <Password - id="{k}_client_secret_oauth" - placeholder="Client Secret" - bind:password={oauths[k]['secret']} - /> - </label> - <div class="flex flex-col gap-1"> - <span class="text-primary font-semibold text-xs">Redirect URL</span> - {#if !baseUrl} - <Alert type="warning" title="No instance base url configured" size="xs"> - Set it in Core settings. The redirect url is built from it, and {k} needs the exact - value. - </Alert> - {:else} - <ClipboardPanel content="{baseUrl}/oauth/callback/{k}" size="sm" /> - {/if} - {#if baseUrlMismatch} - <Alert - type="warning" - title="Does not match the url you are on ({browserOrigin})" - size="xs" - > - This is built from the instance base url. Update it in Core settings if it is - wrong, or {k} will reject the callback. - </Alert> - {/if} - </div> - <div class="flex flex-col gap-2 mb-2"> - <span class="text-xs font-semibold text-emphasis">These credentials are for</span> - {#if !windmillBuiltins.includes(k) || (registryCcCapable(k) && registryAuthCodeCapable(k))} - <ToggleButtonGroup - selected={grantChoice(k)} - onSelected={(v) => setGrantChoice(k, v)} - > - {#snippet children({ item })} - <ToggleButton - value="authorization_code" - label="Authorization code" - showTooltipIcon - tooltip="Users sign in through a browser popup using this app's Client ID and Secret." - {item} + {#if k === 'azure_oauth' || custom || connectConfigTemplates[k]} + <div class="flex flex-col gap-3"> + <span class="text-xs font-semibold text-emphasis">Provider</span> + {#if k === 'azure_oauth'} + <AzureOauthSettings bind:connect_config={oauths[k]['connect_config']} /> + {:else if custom} + <CustomOauth + bind:connect_config={oauths[k]['connect_config']} + requireAuthUrl={authCode} + requireTokenUrl={grants(k).length > 0} + /> + {/if} + {#if connectConfigTemplates[k]} + {@const tmpl = connectConfigTemplates[k]} + <label class="block"> + <span class="text-primary font-semibold text-xs flex gap-2 items-center"> + {#if tmpl.help_url} + <a href={tmpl.help_url} target="_blank">{tmpl.label}</a><ExternalLink + size={12} + /> + {:else} + {tmpl.label} + {/if} + </span> + <input + type="text" + placeholder={tmpl.placeholder} + required={true} + bind:value={instanceInputs[k]} /> - <ToggleButton - value="client_credentials" - label="Client credentials" - showTooltipIcon - tooltip={`Server-to-server. Fill Client ID and Secret to share one service account for every connection, or leave them empty so each user brings their own.${!windmillBuiltins.includes(k) ? ' A Token URL is required below.' : ''}`} - {item} - /> - <ToggleButton - value="both" - label="Both" - showTooltipIcon - tooltip="Offer both flows; the same Client ID and Secret are used for each selected grant." - {item} - /> - {/snippet} - </ToggleButtonGroup> - {:else if registryCcCapable(k)} - <span class="text-xs text-secondary font-normal flex items-center gap-1"> - Client credentials (server-to-server) - <Tooltip - >Fill Client ID and Secret to share one service account, or leave them empty - so each user brings their own.</Tooltip - > - </span> - {:else} - <span class="text-xs text-secondary font-normal" - >Authorization code (browser sign-in)</span - > - {/if} - </div> - {#if k === 'azure_oauth'} - <AzureOauthSettings bind:connect_config={oauths[k]['connect_config']} /> - {:else if !windmillBuiltins.includes(k) && k != 'slack'} - <CustomOauth bind:connect_config={oauths[k]['connect_config']} /> + </label> + {/if} + </div> {/if} - {#if connectConfigTemplates[k]} - {@const tmpl = connectConfigTemplates[k]} - <label class="block pb-2"> - <span class="text-primary font-semibold text-xs flex gap-2 items-center"> - {#if tmpl.help_url} - <a href={tmpl.help_url} target="_blank">{tmpl.label}</a><ExternalLink - size={12} - /> - {:else} - {tmpl.label} - {/if} - </span> - <input - type="text" - placeholder={tmpl.placeholder} - required={true} - bind:value={instanceInputs[k]} - /> + {#if custom} + {@const supportsDesc = + 'The provider accepts the client credentials grant. Users can connect with their own client ID and secret.'} + <!-- Sharing needs the client credentials grant, so it is fixed while sharing is on. --> + {#if shared} + {@render fixedWay('Supports client credentials', supportsDesc)} + {:else} + <div class="flex flex-col gap-1"> + <Toggle + size="xs" + options={{ right: 'Supports client credentials' }} + checked={ownCc} + on:change={(e) => setServerToServer(k, e.detail)} + /> + <span class="text-2xs text-secondary">{supportsDesc}</span> + </div> + {/if} + {/if} + <div class="flex flex-col gap-3"> + <span class="text-xs font-semibold text-emphasis">OAuth app</span> + <label> + <span class="text-primary font-semibold text-xs">Client Id</span> + <input type="text" placeholder="Client Id" bind:value={oauths[k]['id']} /> </label> - {/if} + <div class="flex flex-col gap-1"> + <label for="{k}_client_secret_oauth"> + <span class="text-primary font-semibold text-xs">Client Secret</span> + <Password + id="{k}_client_secret_oauth" + placeholder="Client Secret" + bind:password={oauths[k]['secret']} + /> + </label> + {#if (authCode || shared) && !credsSet} + <span class="text-2xs text-red-500" + >Add the client ID and secret to use this provider.</span + > + {/if} + </div> + {#if !registryCcOnly(k)} + <div class="flex flex-col gap-1"> + <span class="text-primary font-semibold text-xs">Redirect URL</span> + {#if !single} + <span class="text-2xs text-secondary">Only used by authorization code.</span + > + {/if} + {#if !baseUrl} + <Alert type="warning" title="No instance base url configured" size="xs"> + Set it in Core settings. The redirect url is built from it, and {k} needs the + exact value. + </Alert> + {:else} + <ClipboardPanel content="{baseUrl}/oauth/callback/{k}" size="sm" /> + {/if} + {#if baseUrlMismatch} + <Alert + type="warning" + title="Does not match the url you are on ({browserOrigin})" + size="xs" + > + This is built from the instance base url. Update it in Core settings if it + is wrong, or {k} will reject the callback. + </Alert> + {/if} + </div> + {/if} + <div class="flex flex-col gap-3 mt-2"> + {#if single} + {#if registryCcOnly(k)} + {@render fixedWay('Shared client credentials', ccDesc)} + {:else} + {@render fixedWay( + 'Authorization code', + `Users log in with their own ${providerName} account. Each connection acts as the user who logged in.` + )} + {/if} + {:else} + <div class="flex flex-col gap-1"> + <Toggle + size="xs" + options={{ right: 'Authorization code' }} + checked={authCode} + on:change={(e) => setGrant(k, 'authorization_code', e.detail)} + /> + <span class="text-2xs text-secondary" + >Users log in with their own {providerName} account. Each connection acts as + the user who logged in.</span + > + </div> + <div class="flex flex-col gap-1"> + <Toggle + size="xs" + options={{ right: 'Shared client credentials' }} + checked={shared} + on:change={(e) => setSharesCc(k, e.detail, custom)} + /> + <span class="text-2xs text-secondary">{ccDesc}</span> + </div> + {#if !shared && sharesCc(k, savedOauths) && savedOauths[k]?.id && savedOauths[k]?.secret} + <!-- Shared resources fetch the instance's credentials at each refresh. --> + <Alert + type="warning" + title="Existing shared connections will stop working" + size="xs" + > + Resources connected with these shared credentials fail at their next token + refresh. Users have to connect them again with their own client ID and + secret. + </Alert> + {/if} + {/if} + {#if shared && credsSet} + <Alert type="warning" title="Anyone can act as this app" size="xs"> + Any user with write access in any workspace can create a resource that acts + as this app's client ID, without seeing its secret. + </Alert> + {#if $enterpriseLicense} + <Button + variant="default" + unifiedSize="sm" + loading={testingCc[k]} + onclick={() => testClientCredentials(k)} + wrapperClasses="w-fit" + > + Test client credentials + </Button> + {/if} + {/if} + {#if !single && grants(k).length === 0} + <span class="text-2xs text-red-500" + >Turn on at least one option to save this provider.</span + > + {/if} + </div> + </div> {#if k === 'gworkspace'} <div> <Toggle diff --git a/frontend/src/lib/components/AutosaveIndicator.svelte b/frontend/src/lib/components/AutosaveIndicator.svelte index c6aa20ab48..dfd1af8eae 100644 --- a/frontend/src/lib/components/AutosaveIndicator.svelte +++ b/frontend/src/lib/components/AutosaveIndicator.svelte @@ -26,6 +26,7 @@ // take priority over "Loaded from draft" and offers "See others' drafts". othersDraftsCount = 0, onOpenOthersDrafts, + alwaysSaves = false, compact = false }: { workspace: string @@ -36,6 +37,9 @@ loadedFromDraft?: boolean othersDraftsCount?: number onOpenOthersDrafts?: () => void + /** The editor saves every edit whatever the auto-save toggle says, as one with no guard on + * leaving must: the toggle is left out rather than shown with no effect. */ + alwaysSaves?: boolean /** The icon alone, for a bar with no room for the label, which stays for screen readers. */ compact?: boolean } = $props() @@ -151,7 +155,10 @@ ? 'app' : itemKind === 'data_pipeline' ? 'pipeline' - : 'script' + : // The agent editor is the only one showing this for a resource draft. + itemKind === 'resource' + ? 'agent' + : 'script' ) // Each false → true transition fires a hint (others > loaded). Seeded to @@ -210,7 +217,7 @@ // "Enable auto-save" preference — browser-wide, persisted by the syncer. // When off, keystrokes park for Ctrl/Cmd+S and the indicator shows a muted // cloud-off so the idle check-mark can't read as "everything saved". - const autosaveEnabled = $derived(UserDraftDbSyncer.autosaveEnabled) + const autosaveEnabled = $derived(alwaysSaves || UserDraftDbSyncer.autosaveEnabled) let popoverOpen = $state(false) let resetting = $state(false) @@ -328,14 +335,16 @@ per-user — your teammates' editors keep their own. </p> {/if} - <Toggle - size="xs" - checked={autosaveEnabled} - options={{ right: 'Enable auto-save' }} - on:change={(e) => { - UserDraftDbSyncer.autosaveEnabled = e.detail - }} - /> + {#if !alwaysSaves} + <Toggle + size="xs" + checked={autosaveEnabled} + options={{ right: 'Enable auto-save' }} + on:change={(e) => { + UserDraftDbSyncer.autosaveEnabled = e.detail + }} + /> + {/if} {#if othersDraftsCount > 0} <div class="flex flex-col gap-2 border-t pt-3"> <p class="text-primary text-xs"> diff --git a/frontend/src/lib/components/AutoscalingDiagnostics.svelte b/frontend/src/lib/components/AutoscalingDiagnostics.svelte new file mode 100644 index 0000000000..9a23b49103 --- /dev/null +++ b/frontend/src/lib/components/AutoscalingDiagnostics.svelte @@ -0,0 +1,133 @@ +<script lang="ts"> + import { ConfigService, SettingsService } from '$lib/gen' + import { Download, Circle, Square } from 'lucide-svelte' + import { Button } from './common' + import { sendUserToast } from '$lib/toast' + import { displayDate, download } from '$lib/utils' + import { logFeatureUsage } from '$lib/utils/featureUsage' + import { untrack } from 'svelte' + + interface Props { + worker_group: string + /** Bumped by the panel's refresh button to reload the recording state. */ + refreshKey?: number + } + + let { worker_group, refreshKey }: Props = $props() + + let recordingUntil: string | undefined = $state(undefined) + let decisionCount = $state(0) + let busy = $state(false) + + async function loadState() { + try { + const diagnostics = await ConfigService.getAutoscalingDiagnostics({ + workerGroup: worker_group, + includeDecisions: false + }) + recordingUntil = diagnostics.recording_until ?? undefined + decisionCount = diagnostics.decision_count + } catch (e) { + console.error(e) + } + } + + $effect(() => { + refreshKey + worker_group && untrack(() => loadState()) + }) + + // Decisions arrive every 15-20s while recording: keep the count, and so Download, current. + $effect(() => { + if (!recordingUntil) return + const interval = setInterval(() => loadState(), 30_000) + return () => clearInterval(interval) + }) + + async function setRecording(record: boolean) { + busy = true + try { + await ConfigService.setAutoscalingRecording({ + workerGroup: worker_group, + requestBody: { record } + }) + if (record) { + logFeatureUsage('autoscaling_diagnostics', 'recording_started') + sendUserToast( + 'Recording autoscaling decisions for 24h. They are kept for 48h, download them from here.' + ) + } + await loadState() + } catch (e) { + sendUserToast(`Could not change the recording: ${e?.body ?? e}`, true) + } finally { + busy = false + } + } + + async function downloadDiagnostics() { + busy = true + try { + const [diagnostics, config, version] = await Promise.all([ + ConfigService.getAutoscalingDiagnostics({ workerGroup: worker_group }), + ConfigService.getConfig({ name: `worker__${worker_group}` }).catch(() => undefined), + SettingsService.backendVersion().catch(() => undefined) + ]) + const payload = { + worker_group, + version, + exported_at: new Date().toISOString(), + autoscaling: (config as { autoscaling?: unknown } | undefined)?.autoscaling, + ...diagnostics + } + download( + `autoscaling-${worker_group}-${new Date().toISOString().slice(0, 16).replace(':', '-')}.json`, + JSON.stringify(payload, null, 2), + 'application/json' + ) + logFeatureUsage('autoscaling_diagnostics', 'downloaded') + } catch (e) { + sendUserToast(`Could not download the diagnostics: ${e?.body ?? e}`, true) + } finally { + busy = false + } + } +</script> + +<div class="flex flex-row items-center gap-2"> + {#if recordingUntil} + <span class="text-2xs text-secondary">Recording until {displayDate(recordingUntil)}</span> + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: Square }} + disabled={busy} + onClick={() => setRecording(false)} + > + Stop + </Button> + {:else} + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: Circle }} + disabled={busy} + onClick={() => setRecording(true)} + title="Record every autoscaling decision of this worker group, including deciding not to scale, for 24h" + > + Record decisions + </Button> + {/if} + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: Download }} + disabled={busy || decisionCount == 0} + onClick={downloadDiagnostics} + title={decisionCount == 0 + ? 'No decisions recorded in the last 48h' + : `Download the ${decisionCount} decisions recorded in the last 48h`} + > + Download + </Button> +</div> diff --git a/frontend/src/lib/components/AutoscalingEvents.svelte b/frontend/src/lib/components/AutoscalingEvents.svelte index 47626dbb44..27e1ebd2d2 100644 --- a/frontend/src/lib/components/AutoscalingEvents.svelte +++ b/frontend/src/lib/components/AutoscalingEvents.svelte @@ -4,11 +4,12 @@ import { Button, Skeleton } from './common' import { twMerge } from 'tailwind-merge' import TimeAgo from './TimeAgo.svelte' - import { enterpriseLicense } from '$lib/stores' + import { devopsRole, enterpriseLicense, superadmin } from '$lib/stores' import { untrack } from 'svelte' import DataTable from './table/DataTable.svelte' import Head from './table/Head.svelte' import Cell from './table/Cell.svelte' + import AutoscalingDiagnostics from './AutoscalingDiagnostics.svelte' interface Props { worker_group: string @@ -19,6 +20,7 @@ let loading = $state(true) let events: AutoscalingEvent[] | undefined = $state(undefined) let limit = $state(5) + let refreshKey = $state(0) async function loadEvents() { loading = true @@ -49,16 +51,24 @@ {/if} </div> {#if $enterpriseLicense} - <Button - startIcon={{ - icon: RefreshCw, - classes: twMerge(loading ? 'animate-spin' : '') - }} - variant="subtle" - unifiedSize="sm" - on:click={() => loadEvents()} - iconOnly - /> + <div class="flex flex-row items-center gap-2"> + {#if $superadmin || $devopsRole} + <AutoscalingDiagnostics {worker_group} {refreshKey} /> + {/if} + <Button + startIcon={{ + icon: RefreshCw, + classes: twMerge(loading ? 'animate-spin' : '') + }} + variant="subtle" + unifiedSize="sm" + on:click={() => { + loadEvents() + refreshKey++ + }} + iconOnly + /> + </div> {/if} </div> diff --git a/frontend/src/lib/components/BreadcrumbNavPicker.svelte b/frontend/src/lib/components/BreadcrumbNavPicker.svelte index 48479efd92..9ace6f1457 100644 --- a/frontend/src/lib/components/BreadcrumbNavPicker.svelte +++ b/frontend/src/lib/components/BreadcrumbNavPicker.svelte @@ -5,7 +5,8 @@ uses — the workspace pages, then the folders with their flows, scripts and app 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. +highlighted, a workspace page inside Pages with that page highlighted, and a pane of a page with +several (a workspace settings section) among that page's panes. --> <script lang="ts"> import { ChevronDown } from 'lucide-svelte' @@ -21,13 +22,18 @@ highlighted, a workspace page inside Pages with that page highlighted. } from './sessions/previewRouter' import { editPathFor, leafKeyFor, viewPathFor, type WorkspaceItem } from './workspacePicker' import { logFeatureUsage } from '$lib/utils/featureUsage' - import type { PageHeaderItem, PageHeaderSection } from './pageHeaderRegistry.svelte' + import type { + PageHeaderItem, + PageHeaderSection, + PageHeaderSubpage + } from './pageHeaderRegistry.svelte' let { item, pagePath, artifacts, actingWorkspaceId, + subpages, iconSize = 14 }: { /** The item the page is about, to land in its folder. */ @@ -38,6 +44,8 @@ highlighted, a workspace page inside Pages with that page highlighted. artifacts?: PageHeaderSection['navArtifacts'] /** Load from, and navigate within, this workspace rather than the one the app points at. */ actingWorkspaceId?: string + /** The panes of the page at `pagePath`, listed under it and opened on the current one. */ + subpages?: PageHeaderSubpage[] iconSize?: number } = $props() @@ -60,20 +68,23 @@ highlighted, a workspace page inside Pages with that page highlighted. const parts = item?.path?.split('/') ?? [] return parts.length >= 3 ? { kind: 'all', dir: parts.slice(0, -1).join('/') } : undefined }) + const currentSubpage = $derived(subpages?.find((sp) => sp.current)) const initialHighlight = $derived( - artifacts?.currentId - ? artifactKey(artifacts.currentId) - : currentItem - ? leafKeyFor(currentItem.kind, currentItem.path) - : pagePath - ? pageKey(pagePath) - : undefined + currentSubpage + ? pageKey(currentSubpage.href) + : artifacts?.currentId + ? artifactKey(artifacts.currentId) + : 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 + if (!actingWorkspaceId || /[?&]workspace=/.test(href)) return href const sep = href.includes('?') ? '&' : '?' return `${href}${sep}workspace=${encodeURIComponent(actingWorkspaceId)}` } @@ -133,6 +144,7 @@ highlighted, a workspace page inside Pages with that page highlighted. return href ? withWorkspace(href) : undefined }} onPick={pick} + subpages={subpages ? { path: pagePath ?? '', pages: subpages } : undefined} /> {/snippet} </Popover> diff --git a/frontend/src/lib/components/CompareDrafts.svelte b/frontend/src/lib/components/CompareDrafts.svelte index a4e9495ce3..2e2fcc0ae8 100644 --- a/frontend/src/lib/components/CompareDrafts.svelte +++ b/frontend/src/lib/components/CompareDrafts.svelte @@ -116,6 +116,7 @@ draft_only: boolean legacy_draft: boolean raw_app: boolean + resource_type?: string key: string can_write: boolean draft_users?: { username?: string | null }[] @@ -269,36 +270,29 @@ draft?: string stale?: boolean loading?: boolean - /** A resource row that is an AI agent, and the path its draft names. */ - agent?: boolean - draftPath?: string } > >({}) + const isAgentDraft = (item: Row) => + item.draftKind === 'resource' && item.resource_type === 'ai_agent' + async function fetchDraftSummary(item: Row) { if (summaryCache[item.key]) return summaryCache[item.key] = { loading: true } try { - // The drafts list says neither which resources are agents nor where a never-named one - // will deploy, so an agent row is read for its summary and its draft's path. - if (item.draftKind === 'resource') { + // An agent's summary is its resource's description. + if (isAgentDraft(item)) { const r = await ResourceService.getResource({ workspace: currentWorkspaceId, path: item.path, getDraft: true }) - const draft = r.draft as { path?: string; description?: string; resource_type?: string } - const agent = (draft?.resource_type ?? r.resource_type) === 'ai_agent' - summaryCache[item.key] = agent - ? { - agent, - deployed: item.draft_only ? undefined : r.description, - draft: draft?.description ?? r.description, - draftPath: draft?.path, - loading: false - } - : { loading: false } + summaryCache[item.key] = { + deployed: r.description, + draft: (r.draft as { description?: string } | undefined)?.description, + loading: false + } return } const r = (await (item.draftKind === 'script' @@ -337,9 +331,10 @@ for (const item of current) { if ( item.mine && - ((!item.draft_only && - (['script', 'flow', 'app'].includes(item.draftKind) || item.raw_app)) || - item.draftKind === 'resource') && + !item.draft_only && + (['script', 'flow', 'app'].includes(item.draftKind) || + item.raw_app || + isAgentDraft(item)) && !summaryCache[item.key] ) { void fetchDraftSummary(item) @@ -666,7 +661,7 @@ ? `/pipeline/${encodeURIComponent(folder)}?workspace=${encodeURIComponent(currentWorkspaceId)}` : undefined } - if (summaryCache[d.key]?.agent) { + if (isAgentDraft(d)) { return `/agents/edit/${d.path}?workspace=${encodeURIComponent(currentWorkspaceId)}` } const listPage = LIST_PAGE_FOR_KIND[d.draftKind] @@ -726,7 +721,7 @@ {deploymentStatus} {allSelected} selectablePredicate={(item) => isDiscardable(item as unknown as Row)} - isAgent={(item) => !!summaryCache[item.key]?.agent} + isAgent={(item) => isAgentDraft(item as unknown as Row)} selectBlockedReason={(item) => blockedReason(item as unknown as Row)} onToggleItem={toggleItem} onSelectAll={selectAll} @@ -804,7 +799,7 @@ {@const oldSummary = cache?.deployed ?? draftItem.summary} {@const newSummary = cache?.draft ?? draftItem.summary} <WorkspaceDeployItemSummary - path={cache?.agent ? (cache.draftPath ?? draftItem.path) : displayPath(draftItem)} + path={displayPath(draftItem)} {editUrl} {oldSummary} {newSummary} @@ -817,13 +812,7 @@ {#snippet itemPath(item)} {@const draftItem = item as unknown as Row} - {@const agent = summaryCache[draftItem.key]?.agent - ? summaryCache[draftItem.key] - : undefined} - {#if agent} - <!-- Titled by its summary like a script; a summary-less one is titled by this path. --> - {#if agent.draft}{agent.draftPath ?? draftItem.path}{/if} - {:else if draftItem.kind === 'resource' || draftItem.kind === 'variable' || draftItem.kind === 'resource_type'} + {#if (draftItem.kind === 'resource' && !isAgentDraft(draftItem)) || draftItem.kind === 'variable' || draftItem.kind === 'resource_type'} <!-- drawer-only items show their path as the title; keep this line empty --> {:else if !draftItem.draft_only && draftItem.draft_path && draftItem.draft_path !== draftItem.path} <!-- Path rename: a *deployed* item's draft moves it to a new path. Strike @@ -842,7 +831,7 @@ {@const others = otherDraftUsers(draftItem)} <div class="flex items-center gap-1"> <Badge color="gray" size="xs"> - {summaryCache[draftItem.key]?.agent ? 'agent' : kindLabel(draftItem.draftKind)} + {isAgentDraft(draftItem) ? 'agent' : kindLabel(draftItem.draftKind)} </Badge> <DraftBadge is_draft={true} diff --git a/frontend/src/lib/components/CompareWorkspaces.svelte b/frontend/src/lib/components/CompareWorkspaces.svelte index 4ce7fb1504..e265c453dc 100644 --- a/frontend/src/lib/components/CompareWorkspaces.svelte +++ b/frontend/src/lib/components/CompareWorkspaces.svelte @@ -51,6 +51,7 @@ diffRemovesInTarget, getItemValue, getOnBehalfOf, + triggerCiTestsForBatch, type DeployPermission, type DeployResult } from '$lib/utils_workspace_deploy' @@ -848,18 +849,48 @@ workspaceFrom, workspaceTo: workspaceToDeployTo, onBehalfOf: getOnBehalfOfForDeploy(statusKey, kind), - onBehalfOfPrincipal: getOnBehalfOfPermissionedAsForDeploy(statusKey, kind) + onBehalfOfPrincipal: getOnBehalfOfPermissionedAsForDeploy(statusKey, kind), + skipCiTests: true }) } if (result.success) { deploymentStatus[statusKey] = { status: 'deployed' } + if (kind === 'folder' && !removes) { + warnOnAddedFolderOwners(path, workspaceFrom, workspaceToDeployTo) + } } else { deploymentStatus[statusKey] = { status: 'failed', error: result.error } sendUserToast(`Failed to deploy ${statusKey}: ${result.error}`, 'error') } } + // A non-admin can't drop their own ownership of a folder (the folder UPDATE policy + // rejects a row they don't own), so updateFolder keeps them as an owner. The folder then + // never matches its source, and the conflict comes back on every compare unless we say why. + async function warnOnAddedFolderOwners(path: string, workspaceFrom: string, workspaceTo: string) { + const name = path.replace(/^f\//, '') + try { + const [source, target, me] = await Promise.all([ + FolderService.getFolder({ workspace: workspaceFrom, name }), + FolderService.getFolder({ workspace: workspaceTo, name }), + UserService.whoami({ workspace: workspaceTo }) + ]) + const owner = `u/${me.username}` + if (!me.is_admin && target.owners.includes(owner) && !source.owners.includes(owner)) { + sendUserToast( + `${path} still differs in ${workspaceTo}: it kept ${owner} as owner, because a non-admin can't remove their own ownership of a folder. To clear it, make ${owner} owner of ${path} in ${workspaceFrom} too, or deploy as an admin of ${workspaceTo}.`, + 'warning', + [], + undefined, + 15000 + ) + } + } catch { + // The deploy itself succeeded; the next compare still shows the difference. + } + } + let deploymentErrorMessage = $state('') // 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 @@ -922,6 +953,7 @@ let anyFailed = false // Datatables whose migrations deployed cleanly — candidates for a run prompt. const deployedMigrationDatatables = new Set<string>() + const ciTested: { kind: 'script' | 'flow' | 'resource'; path: string }[] = [] const applyAll = async () => { for (const itemKey of sortedItems) { const deployable = deployableItems.find((d) => d.key === itemKey) @@ -937,6 +969,13 @@ anyFailed = true } else if (deployable.kind === 'datatable_migration') { deployedMigrationDatatables.add(deployable.path.split('/')[0]) + } else if ( + (deployable.kind === 'script' || + deployable.kind === 'flow' || + deployable.kind === 'resource') && + !comparison?.diffs.some((d) => getItemKey(d) === itemKey && removesInTarget(d)) + ) { + ciTested.push({ kind: deployable.kind, path: deployable.path }) } } } @@ -947,6 +986,10 @@ await (mergeIntoParent ? applyAll() : asSyncDeploy(applyAll)) deploying = false deselectAll() + // The tests are held back while the batch deploys, so each one runs against all of it. + triggerCiTestsForBatch(to, ciTested).catch((e) => + sendUserToast(`Failed to queue CI tests: ${e?.body ?? e?.message ?? e}`, true) + ) await maybePromptRunMigrations(deployedMigrationDatatables, to) diff --git a/frontend/src/lib/components/CronInput.svelte b/frontend/src/lib/components/CronInput.svelte index e38f7b6458..50c450bcb7 100644 --- a/frontend/src/lib/components/CronInput.svelte +++ b/frontend/src/lib/components/CronInput.svelte @@ -12,6 +12,7 @@ import { safeSelectItems } from './select/utils.svelte' import { untrack } from 'svelte' import TextInput from './text_input/TextInput.svelte' + import { latestRequest } from '$lib/utils/latestRequest' interface Props { schedule: string @@ -68,13 +69,19 @@ let daysOfWeek: string[] = $state([]) let UTCTime: string = $state('') + // A slower reply for an earlier cron or timezone must not overwrite the current preview. + const previewRequests = latestRequest() async function handleScheduleInput(input: string, timezone: string): Promise<void> { + const isLatest = previewRequests.start() try { - preview = await ScheduleService.previewSchedule({ + const result = await ScheduleService.previewSchedule({ requestBody: { schedule: formatCron(input), timezone, cron_version: cronVersion } }) + if (!isLatest()) return + preview = result validCRON = true } catch (err) { + if (!isLatest()) return if (err.status == 400 && err.body.includes('cron')) { validCRON = false } else { @@ -139,7 +146,9 @@ : [{ value: timezone, label: timezone, group: 'Current' }, ...timezoneItems] ) $effect(() => { + // The preview is computed in the timezone, so changing it must refetch. schedule + timezone untrack(() => { !emptyString(schedule) && handleScheduleInput(schedule, timezone) }) diff --git a/frontend/src/lib/components/CustomOauth.svelte b/frontend/src/lib/components/CustomOauth.svelte index 942dc553d7..44dc9e22f7 100644 --- a/frontend/src/lib/components/CustomOauth.svelte +++ b/frontend/src/lib/components/CustomOauth.svelte @@ -6,7 +6,16 @@ import Toggle from './Toggle.svelte' import Tooltip from './Tooltip.svelte' - let { connect_config = $bindable() } = $props() + let { + connect_config = $bindable(), + requireAuthUrl = false, + requireTokenUrl = false + }: { + connect_config: any + /** A way that is on needs this URL: an empty one is flagged under its field. */ + requireAuthUrl?: boolean + requireTokenUrl?: boolean + } = $props() run(() => { if (!connect_config) { @@ -35,6 +44,9 @@ placeholder="https://github.com/login/oauth/authorize" bind:value={connect_config.auth_url} /> + {#if requireAuthUrl && !connect_config.auth_url} + <span class="text-2xs text-red-500">Add the auth URL to use this provider.</span> + {/if} </label> <label class="flex flex-col gap-1"> <span class="text-emphasis font-semibold text-xs"> Token URL</span> @@ -43,6 +55,9 @@ placeholder="https://github.com/login/oauth/access_token" bind:value={connect_config.token_url} /> + {#if requireTokenUrl && !connect_config.token_url} + <span class="text-2xs text-red-500">Add the token URL to use this provider.</span> + {/if} </label> <!-- svelte-ignore a11y_label_has_associated_control --> <label class="flex flex-col gap-1"> diff --git a/frontend/src/lib/components/DBManagerContent.svelte b/frontend/src/lib/components/DBManagerContent.svelte index 8894043688..9543f7a9e3 100644 --- a/frontend/src/lib/components/DBManagerContent.svelte +++ b/frontend/src/lib/components/DBManagerContent.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import { dbManagerTabsStorageKey, dbTableLayoutStorageKey } from './dbManagerDrawerModel.svelte' import { DbManagerTabs, type DbManagerTabKind } from './dbManagerTabs.svelte' import DbSqlTab from './DbSqlTab.svelte' @@ -279,7 +280,7 @@ export const tabsModel = () => tabs </script> -<svelte:window +<HostWindow onkeydown={(e) => { if (e.key === 'Escape') { if (replResultData) { diff --git a/frontend/src/lib/components/DBTable.svelte b/frontend/src/lib/components/DBTable.svelte index 03f26ced21..0ea2ec0fc5 100644 --- a/frontend/src/lib/components/DBTable.svelte +++ b/frontend/src/lib/components/DBTable.svelte @@ -33,6 +33,7 @@ </script> <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import { sendUserToast } from '$lib/toast' import { Button } from './common' import { @@ -1026,6 +1027,8 @@ if (editing) cancelEdit() closeFormatOnOutsideClick(e) }} +/> +<HostWindow onkeydown={(e) => { if (formatting && e.key === 'Escape') formatting = undefined }} diff --git a/frontend/src/lib/components/DdlMigrationGuard.svelte b/frontend/src/lib/components/DdlMigrationGuard.svelte index 0dab262fd0..b9a3515efd 100644 --- a/frontend/src/lib/components/DdlMigrationGuard.svelte +++ b/frontend/src/lib/components/DdlMigrationGuard.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import { Button } from './common' import Modal2 from './common/modal/Modal2.svelte' import NewDataTableMigrationModal from './workspaceSettings/NewDataTableMigrationModal.svelte' @@ -136,7 +137,7 @@ } </script> -<svelte:window onkeydown={onKeyDown} /> +<HostWindow onkeydown={onKeyDown} /> <Modal2 title={promptStatements.length > 1 ? 'Schema changes detected' : 'Schema change detected'} diff --git a/frontend/src/lib/components/DedicatedWorkersSelector.svelte b/frontend/src/lib/components/DedicatedWorkersSelector.svelte index c355f1cf50..6bcdbd3eb7 100644 --- a/frontend/src/lib/components/DedicatedWorkersSelector.svelte +++ b/frontend/src/lib/components/DedicatedWorkersSelector.svelte @@ -26,7 +26,7 @@ import { SvelteMap } from 'svelte/reactivity' import { untrack } from 'svelte' import BarsStaggered from './icons/BarsStaggered.svelte' - import { isDedicatedPattern, parseTag } from './dedicated_worker' + import { canonicalTag, isDedicatedPattern, parseTag } from './dedicated_worker' import Tooltip from './Tooltip.svelte' // A "Runnable" is a script or flow with dedicated_worker=true @@ -481,7 +481,7 @@ language: script.language ?? 'unknown', type: 'script', path: script.path, - selected: selectedTags.includes(tag), + selected: isSelected(tag), workspaceDeps: depsMap.get(script.path) }) } @@ -496,7 +496,7 @@ language: 'flow', type: 'flow', path: flow.path, - selected: selectedTags.includes(tag), + selected: isSelected(tag), runners: undefined, loadingRunners: false, expanded: false @@ -541,17 +541,22 @@ function updateSelectedTags() { // Keep tags from other workspaces, update only the currently visible ones const visibleTags = new Set(runnables.map((r) => r.tag)) - const otherTags = selectedTags.filter((t) => !visibleTags.has(t)) + const otherTags = selectedTags.filter((t) => !visibleTags.has(canonicalTag(t))) for (const r of runnables) if (coveringPattern(r)) r.selected = false const newVisibleTags = runnables.filter((r) => r.selected).map((r) => r.tag) selectedTags = [...otherTags, ...newVisibleTags] onchange?.(selectedTags) } + // `tag` is canonical; a saved entry may be spelled with a leading `/` + function isSelected(tag: string): boolean { + return selectedTags.some((t) => canonicalTag(t) === tag) + } + let patternInput = $state('') let patternTag = $derived( selectedWorkspace && isDedicatedPattern(patternInput.trim()) - ? `${selectedWorkspace}:${patternInput.trim()}` + ? canonicalTag(`${selectedWorkspace}:${patternInput.trim()}`) : undefined ) @@ -569,7 +574,7 @@ } function addPattern() { - if (!patternTag || selectedTags.includes(patternTag)) return + if (!patternTag || isSelected(patternTag)) return selectedTags = [...selectedTags, patternTag] patternInput = '' updateSelectedTags() @@ -578,7 +583,7 @@ function removeTag(tag: string) { selectedTags = selectedTags.filter((t) => t !== tag) // Also update runnable state if visible - const runnable = runnables.find((r) => r.tag === tag) + const runnable = runnables.find((r) => r.tag === canonicalTag(tag)) if (runnable) { runnable.selected = false } @@ -912,7 +917,7 @@ > {#if via} <span class="text-2xs text-hint flex-shrink-0" - >via {via.substring(via.indexOf(':') + 1)}</span + >via {parseTag(via)?.path}</span > {/if} {#if runnable.type === 'flow' && runnable.runners} diff --git a/frontend/src/lib/components/DevWorkspaceSetting.svelte b/frontend/src/lib/components/DevWorkspaceSetting.svelte index 72fa9da89a..f317fc5964 100644 --- a/frontend/src/lib/components/DevWorkspaceSetting.svelte +++ b/frontend/src/lib/components/DevWorkspaceSetting.svelte @@ -546,7 +546,7 @@ /> {/if} </div> - <div class="flex gap-2"> + <div class="flex flex-wrap gap-2"> <Button variant="accent" disabled={busy || !selectedDevId || !!candidateClash} diff --git a/frontend/src/lib/components/DisplayResult.svelte b/frontend/src/lib/components/DisplayResult.svelte index afadcb5741..95d7e0ab2b 100644 --- a/frontend/src/lib/components/DisplayResult.svelte +++ b/frontend/src/lib/components/DisplayResult.svelte @@ -7,7 +7,13 @@ import { parseDbtRun } from '$lib/components/dbt/parseDbtRun' import { copyToClipboard, parseS3Object, roughSizeOfObject } from '$lib/utils' import ExpandableImage from '$lib/components/common/image/ExpandableImage.svelte' - import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile' + import { + downloadBlob, + downloadViaClient, + fetchViaClient, + shouldDownloadViaClient + } from '$lib/utils/downloadFile' + import { sendUserToast } from '$lib/toast' import { appendViewToken } from '$lib/viewToken' import { Badge, Button, Drawer, DrawerContent } from './common' import { @@ -38,6 +44,8 @@ import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' import MapResult from './MapResult.svelte' + import ChartResult from './display/ChartResult.svelte' + import { isChartResult } from './display/displayCatalog' import DownloadCsv from './table/DownloadCsv.svelte' import { convertJsonToCsv } from './table/tableUtils' import Tooltip from './Tooltip.svelte' @@ -89,6 +97,7 @@ | 'nondisplayable' | 'pdf' | 'aiagent' + | 'chart' | undefined let resultKind: ResultKind = $state() /** Kinds whose renderer leaves the page: S3/ducklake previews fetch the file or @@ -258,6 +267,50 @@ ) let resultDownloadName = $derived(`${filename ?? 'result'}.json`) + // A result over the backend's inline cap arrives as 'WINDMILL_TOO_BIG'. Ask the backend for + // `file.filename` alone to tell a `{ file: { content, filename } }` result. The root + // `{ file, filename }` shape is a file only when those are its sole keys, which cannot be + // checked without reading the large value, so it keeps the JSON download. + let tooBigFilename: string | undefined = $state(undefined) + let downloadingTooBigFile = $state(false) + async function fetchResultAt(apiPath: string, jsonPath: string): Promise<unknown> { + const r = await fetchViaClient( + `${apiPath}${apiPath.includes('?') ? '&' : '?'}json_path=${jsonPath}` + ) + if (!r.ok) throw new Error(`${r.status} ${r.statusText}`) + return r.json() + } + $effect(() => { + tooBigFilename = undefined + const apiPath = result === 'WINDMILL_TOO_BIG' ? resultApiPath : undefined + if (!apiPath) return + let stale = false + fetchResultAt(apiPath, 'file.filename').then( + (name) => { + if (!stale && typeof name === 'string') tooBigFilename = name + }, + () => {} + ) + return () => (stale = true) + }) + async function downloadTooBigFile(apiPath: string, name: string) { + downloadingTooBigFile = true + try { + const content = await fetchResultAt(apiPath, 'file.content') + if (typeof content !== 'string' || !content) throw new Error('the result has no file content') + const bin = atob(content) + // Filled byte by byte: a per-character array is several times the file's size + const bytes = new Uint8Array(bin.length) + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i) + // A blob, not a data: URL, which browsers cap well below a large file's size + downloadBlob(new Blob([bytes]), name) + } catch (e) { + sendUserToast(`Download failed: ${e instanceof Error ? e.message : e}`, true) + } finally { + downloadingTooBigFile = false + } + } + function checkIfS3(result: any, keys: string[]) { return keys.includes('s3') && typeof result.s3 === 'string' } @@ -378,7 +431,11 @@ } if (keys.length != 0) { - if ( + // Only a chart the catalog accepts: any other `{ chart }` result stays JSON. The + // catalog caps its rows, so it is exempt from the display size limit. + if (keys.length == 1 && keys[0] === 'chart' && isChartResult(result)) { + return 'chart' + } else if ( keys.length == 1 && [...IMG_KINDS, 'html', 'map', 'pdf', 'file', 'error'].includes(keys[0]) ) { @@ -907,6 +964,8 @@ {@html renderResultMarkup(result.html)} {/if} </div> + {:else if !forceJson && resultKind === 'chart'} + <ChartResult chart={result.chart} /> {:else if !forceJson && resultKind === 'map'} <div class="h-full" data-interactive> <MapResult @@ -1318,6 +1377,19 @@ > </div> {:else} + {#if tooBigFilename && resultApiPath} + <div class="flex"> + <Button + onclick={() => downloadTooBigFile(resultApiPath!, tooBigFilename!)} + disabled={downloadingTooBigFile} + startIcon={{ icon: Download }} + variant="subtle" + unifiedSize="sm" + > + Download {tooBigFilename} + </Button> + </div> + {/if} {#if largeObject} <div class="text-xs text-emphasis" >{#if resultApiPath && shouldDownloadViaClient()} diff --git a/frontend/src/lib/components/DraftBadge.svelte b/frontend/src/lib/components/DraftBadge.svelte index 4b37d7ae6e..be3fe0a86b 100644 --- a/frontend/src/lib/components/DraftBadge.svelte +++ b/frontend/src/lib/components/DraftBadge.svelte @@ -19,6 +19,7 @@ */ import Popover from './meltComponents/Popover.svelte' import Tooltip from './meltComponents/Tooltip.svelte' + import { userColorClass, userInitials } from './userInitials' import { Badge } from './common' import Button from './common/button/Button.svelte' import type DiffDrawer from './DiffDrawer.svelte' @@ -57,6 +58,9 @@ * slightly smaller — for tight spots like the diff-tree sidebar. The hover * popover is unchanged. */ iconOnly?: boolean + /** The `resource` draft is an AI agent's, which has an editor of its own and is authored + * under the flow right rather than the resource one. */ + agent?: boolean } let { @@ -69,7 +73,8 @@ path = undefined, onMigrated = undefined, allowFork = true, - iconOnly = false + iconOnly = false, + agent = false }: Props = $props() // Authed user lands first; everyone else keeps the backend's ordering. @@ -82,35 +87,16 @@ return [self, ...rest] }) - /** Two-letter initials; `john.doe` → `JD`, `alice` → `AL`, no username → `?`. */ function initials(u: DraftUser): string { - const name = u.username - if (!name) return '?' - const parts = name.split(/[._\-\s]+/).filter(Boolean) - if (parts.length >= 2) { - return (parts[0][0] + parts[1][0]).toUpperCase() - } - return name.slice(0, 2).toUpperCase() + return userInitials(u.username) } function fullLabel(u: DraftUser): string { return u.username ?? 'Legacy workspace draft' } - // Deterministic color per username, same circle across rows. - const PALETTE = [ - 'bg-blue-500', - 'bg-emerald-500', - 'bg-amber-500', - 'bg-rose-500', - 'bg-violet-500', - 'bg-cyan-500' - ] function colorFor(u: DraftUser): string { - const name = u.username ?? '' - let hash = 0 - for (let i = 0; i < name.length; i++) hash = (hash * 31 + name.charCodeAt(i)) >>> 0 - return PALETTE[hash % PALETTE.length] + return userColorClass(u.username) } // First 3 circles when ≤3 users; first 2 + "+N" overflow when 4+. Sliced from @@ -133,11 +119,22 @@ const actionsEnabled = $derived(!!workspace && !!itemKind && !!path && draft_users.length > 0) // The editors these open are the full ones, which a role without code cannot use. const canOpenEditor = $derived( - !!itemKind && $roleCapabilities.code && roleCanAuthor(itemKind, $roleCapabilities) + agent + ? roleCanAuthor('agent', $roleCapabilities) + : !!itemKind && $roleCapabilities.code && roleCanAuthor(itemKind, $roleCapabilities) + ) + const editHref = $derived( + !itemKind || !path ? undefined : agent ? `/agents/edit/${path}` : editRouteFor(itemKind, path) ) const kindLabel = $derived( - itemKind === 'flow' ? 'flow' : itemKind === 'app' || itemKind === 'raw_app' ? 'app' : 'script' + agent + ? 'agent' + : itemKind === 'flow' + ? 'flow' + : itemKind === 'app' || itemKind === 'raw_app' + ? 'app' + : 'script' ) // "Only you can see this {kind}" — true when the authed user owns the @@ -392,12 +389,12 @@ </span> {#if actionsEnabled && isSelf} <!-- Own draft: jump straight into the editor. --> - {#if canOpenEditor && itemKind && path} + {#if canOpenEditor && editHref} <Button variant="subtle" size="xs3" startIcon={{ icon: Pencil }} - href={editRouteFor(itemKind, path)} + href={editHref} > Edit </Button> diff --git a/frontend/src/lib/components/DrillPicker.svelte b/frontend/src/lib/components/DrillPicker.svelte index 00fffabc94..80635a55c1 100644 --- a/frontend/src/lib/components/DrillPicker.svelte +++ b/frontend/src/lib/components/DrillPicker.svelte @@ -13,7 +13,8 @@ level *up*. Filter (internal or `externalFilter`) is global across all leaves and ignores the current scope. --> <script lang="ts" generics="L"> - import { ChevronLeft, ChevronRight, Loader2 } from 'lucide-svelte' + import { CheckCircle2, ChevronLeft, ChevronRight, Loader2 } from 'lucide-svelte' + import { fade, fly } from 'svelte/transition' import TextInput from '$lib/components/text_input/TextInput.svelte' import SearchItems from '$lib/components/SearchItems.svelte' import Portal from '$lib/components/Portal.svelte' @@ -30,6 +31,7 @@ leaves and ignores the current scope. type DrillBranch, type DrillIcon, type DrillLeaf, + type DrillLeafAction, type DrillNode } from './drillPicker' import Badge from '$lib/components/common/badge/Badge.svelte' @@ -39,7 +41,10 @@ leaves and ignores the current scope. interface Props { tree: DrillNode<L>[] - onPick: (leaf: DrillLeaf<L>) => void + /** Picking a leaf: a click, or Enter on its highlighted row. Without it, a click on a leaf + * does nothing and Enter runs the highlighted row's selected `leafActions` button, for a + * picker whose rows act only through their buttons. */ + onPick?: (leaf: DrillLeaf<L>) => void /** Drill path to land on initially. Empty = root. */ initialScope?: string[] /** Composite key of the row to highlight initially. */ @@ -87,13 +92,22 @@ leaves and ignores the current scope. leaf: DrillLeaf<L> ) => { icon: DrillIcon; label: string; title: string; run: () => void } | undefined /** Status badge on the right of a leaf row. Returns `undefined` for a leaf with - * nothing to report. The hover action, when there is one, covers it. */ + * nothing to report. The hover action, when there is one, covers it. With `leafActions` it + * is plain text and `color` is unused. */ leafBadge?: (leaf: DrillLeaf<L>) => { label: string; color: BadgeColor } | undefined /** Where picking a leaf navigates, for a host whose pick is a navigation. The row then * renders as a link: a plain click still goes through `onPick`, while a middle or * ⌘/Ctrl-click opens it in a new tab — taking ⌘/Ctrl-click from `leafAction`, which * keeps ⌘/Ctrl-Enter. */ leafHref?: (leaf: DrillLeaf<L>) => string | undefined + /** What a leaf row offers, laid over its end while the row is highlighted (hovered or reached + * with the arrow keys), so the row does not reflow: the `preferred` one (else the first) as a + * button, which Enter runs when there is no `onPick`, and the others in its dropdown. In + * place of `leafAction`, not with it. */ + leafActions?: (leaf: DrillLeaf<L>) => DrillLeafAction[] | undefined + /** What a `leafActions` button just did on a leaf ("Read granted"), shown over the row's + * end, highlighted or not, while it returns a text. */ + leafDone?: (leaf: DrillLeaf<L>) => string | undefined } let { @@ -113,7 +127,9 @@ leaves and ignores the current scope. rowTooltip, leafAction, leafBadge, - leafHref + leafHref, + leafActions, + leafDone }: Props = $props() let searchInput: TextInput | undefined = $state() @@ -302,7 +318,9 @@ leaves and ignores the current scope. // Ignored until the user actually moves the mouse. Prevents the // cursor (parked over a row) from clobbering keyboard-driven // selection when the layout shifts beneath it. - if (mouseActive) highlightedKey = key + // A row's open menu sits over the rows below it, and the pointer crosses them to reach it: + // moving the highlight would take the menu's button away. + if (mouseActive && !actionMenuOpen) highlightedKey = key } /** `alt` picks the row's second action (see `leafAction`) rather than the row @@ -310,6 +328,10 @@ leaves and ignores the current scope. * that only appears on hover. A leaf with no second action ignores it. */ function pick(leaf: DrillLeaf<L>, alt = false) { if (leaf.disabled) return + if (!onPick) { + if (leaf.key === highlightedKey) runMainAction() + return + } // The second action is the row's other destination (its editor, for the deployed page // this tab shows), so it stays available on the current row the plain pick skips. if (alt) { @@ -323,6 +345,25 @@ leaves and ignores the current scope. onPick(leaf) } + function runMainAction() { + const action = mainAction + if (action && !action.disabled && !action.loading) runAction(action) + } + + /** The button area's width when each row's action ran, the least its success pill takes. Read + * from `actionsWidth` live, the pill would resize on hover, which moves the highlighted row. */ + let pillWidths: Record<string, number> = $state({}) + function runAction(action: DrillLeafAction) { + if (highlightedKey) pillWidths[highlightedKey] = actionsWidth + action.run() + } + + /** Fades out what lies under the highlighted row's buttons, which sit over its end. */ + function fadeUnder(width: number): string { + const mask = `linear-gradient(to left, transparent ${width}px, #000 ${width + 16}px)` + return `mask-image: ${mask}; -webkit-mask-image: ${mask}` + } + // Single shared hover tooltip (opt-in via `rowTooltip`): one floating node // re-anchored to the hovered row, instead of a popover per row — rows can // number in the hundreds. Portaled to body because the picker often lives @@ -385,6 +426,17 @@ leaves and ignores the current scope. } function handleSearchKeydown(e: KeyboardEvent) { + // A row's button has focus only after a click: it keeps its own keys, and Enter must not + // also reach the row. ↑/↓ and Escape return to the search field. + if ((e.target as HTMLElement | null)?.closest?.('[data-drill-action]')) { + if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Escape') { + e.preventDefault() + e.stopPropagation() + focus() + if (e.key !== 'Escape') moveHighlight(e.key === 'ArrowDown' ? 1 : -1) + } + return + } if (e.key === 'ArrowDown') { e.preventDefault() e.stopPropagation() @@ -400,6 +452,8 @@ leaves and ignores the current scope. // highlighted row so an unrelated Tab in an empty picker still // falls through to natural focus movement. if (e.key === 'Tab' && !highlightedKey) return + // Without `onPick`, Enter on a leaf runs its selected button, which Tab must not do. + if (e.key === 'Tab' && !onPick && leafForKey(highlightedKey!)) return e.preventDefault() e.stopPropagation() mouseActive = false @@ -484,6 +538,35 @@ leaves and ignores the current scope. }) const branchLoading = $derived(currentBranch ? (currentBranch.loading ?? false) : rootLoading) + + const highlightedNode = $derived.by<DrillNode<L> | undefined>(() => { + if (!highlightedKey) return undefined + if (isSearching) return (searchedItems ?? []).find((r) => r.leaf.key === highlightedKey)?.leaf + return entryList.find((e) => e.key === highlightedKey)?.node + }) + + const highlightedActions = $derived( + highlightedNode?.type === 'leaf' && !highlightedNode.disabled + ? (leafActions?.(highlightedNode) ?? []) + : [] + ) + const mainAction = $derived(highlightedActions.find((a) => a.preferred) ?? highlightedActions[0]) + const otherActions = $derived(highlightedActions.filter((a) => a !== mainAction)) + let actionMenuOpen = $state(false) + + /** Answers an Escape a host takes before the picker can: closes a row's dropdown, which hands + * focus back to its chevron, or leaves a row's button for the search field. False when neither + * applies, so the host closes instead. */ + export function escape(target: EventTarget | null): boolean { + if (actionMenuOpen) { + actionMenuOpen = false + return true + } + if (!(target as HTMLElement | null)?.closest?.('[data-drill-action]')) return false + focus() + return true + } + let actionsWidth = $state(0) </script> <SearchItems @@ -525,6 +608,9 @@ leaves and ignores the current scope. {@const action = leaf.disabled ? undefined : leafAction?.(leaf)} {@const badge = leafBadge?.(leaf)} {@const href = leaf.disabled ? undefined : leafHref?.(leaf)} + {@const inert = !onPick} + {@const actions = isHl ? highlightedActions : []} + {@const done = leafDone?.(leaf)} <!-- The row's action sits BESIDE the option rather than inside it: a button nested in a button is invalid markup. The wrapper carries the row's padding, highlight and hover group so the two still read as one row. --> @@ -534,99 +620,171 @@ leaves and ignores the current scope. <!-- A disabled option dims through `disabled:opacity-50` and shows its cursor on this wrapper: the base `button:disabled` rule in tailwind.config.cjs outranks a plain `opacity-50` and turns pointer events off on the button itself. --> + <!-- `leafActions` show only on the highlighted row, so a pointer that comes back after the + arrow keys moved the highlight takes it on its first move, not on the next row it enters. --> <div - class="group flex items-center transition-colors pr-3 {baseClass} {isHl + class="group relative flex items-center transition-colors pr-3 {baseClass} {isHl ? 'bg-surface-hover' : ''} {leaf.disabled ? 'cursor-not-allowed' : ''}" onmouseenter={(e) => { setHoverHighlight(key) tooltipEnter(e.currentTarget as HTMLElement, leaf) }} + onmousemove={leafActions && !isHl ? () => setHoverHighlight(key) : undefined} onmouseleave={tooltipLeave} > - <svelte:element - this={href ? 'a' : 'button'} - type={href ? undefined : 'button'} - {href} - id={idFor(key)} - role="option" - aria-selected={isHl} - data-nav-key={key} - aria-current={isCur ? 'true' : undefined} - aria-label={tip ? `${leaf.label} — ${tip}` : undefined} - class="min-w-0 flex-1 text-left flex items-center gap-2 pl-3 {isCur - ? 'cursor-default text-emphasis font-medium' - : 'text-[color:inherit]'} disabled:opacity-50" - disabled={href ? undefined : leaf.disabled} - tabindex={0} - onmousedown={(e: MouseEvent) => e.preventDefault()} - onclickcapture={(e: MouseEvent) => { - // Capture, not a delegated onclick: the picker is portalled outside the app root, - // where a delegated handler runs after SvelteKit's link handler has already - // followed the href, too late for preventDefault to keep a plain click on `pick`. - if (href && isNewTabClick(e)) return - e.preventDefault() - pick(leaf, e.metaKey || e.ctrlKey) - }} + <!-- With `leafActions`, what fades out under the row's buttons; `contents` otherwise. --> + <div + class={leafActions ? 'min-w-0 flex-1 flex items-center' : 'contents'} + style={actions.length ? fadeUnder(actionsWidth) : undefined} > - {@render defaultLeafIcon(leaf)} - <!-- 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]' : ''}" + <svelte:element + this={href ? 'a' : inert ? 'div' : 'button'} + type={href || inert ? undefined : 'button'} + {href} + id={idFor(key)} + role="option" + aria-selected={isHl} + aria-disabled={inert && leaf.disabled ? 'true' : undefined} + data-nav-key={key} + aria-current={isCur ? 'true' : undefined} + aria-label={tip ? `${leaf.label} — ${tip}` : undefined} + class="min-w-0 flex-1 text-left flex items-center gap-2 pl-3 {isCur + ? 'cursor-default text-emphasis font-medium' + : 'text-[color:inherit]'} {inert + ? leaf.disabled + ? 'opacity-50' + : 'cursor-default' + : 'disabled:opacity-50'}" + disabled={href || inert ? undefined : leaf.disabled} + tabindex={inert ? -1 : 0} + onmousedown={(e: MouseEvent) => e.preventDefault()} + onclickcapture={inert + ? undefined + : (e: MouseEvent) => { + // Capture, not a delegated onclick: the picker is portalled outside the app root, + // where a delegated handler runs after SvelteKit's link handler has already + // followed the href, too late for preventDefault to keep a plain click on `pick`. + if (href && isNewTabClick(e)) return + e.preventDefault() + pick(leaf, e.metaKey || e.ctrlKey) + }} > - {#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"> - {secondary ?? leaf.secondary} - </div> - {:else} - <div class="text-xs text-primary font-normal font-mono truncate"> - {secondary ?? leaf.label} - </div> + {@render defaultLeafIcon(leaf)} + <!-- 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"> + {secondary ?? leaf.secondary} + </div> + {:else} + <div + class="text-xs text-primary font-normal truncate {secondary === undefined && + leaf.plainLabel + ? '' + : 'font-mono'}" + > + {secondary ?? leaf.label} + </div> + {/if} + </div> + </svelte:element> + {#if leafActions} + <!-- Plain text beside the row's buttons, which sit over it while the row is + highlighted: a filled badge reads as one more button. --> + {#if badge} + <span class="shrink-0 pl-2 text-xs text-secondary">{badge.label}</span> + {/if} + <!-- Keyed on the props rather than on this leaf's own badge or action, so a picker + that has either holds the column open on every row: paths then truncate at one + column and the button lands in the same place down the list. --> + {:else if leafBadge || leafAction} + <!-- Both sit in one grid cell so they cross-fade in place rather than sitting + side by side or shifting the row as one replaces the other. --> + <div class="shrink-0 w-[4.5rem] grid justify-items-end items-center pl-2"> + {#if action} + <!-- `invisible`, not `hidden`: display cannot be transitioned, while + visibility both fades with opacity and keeps the button out of the tab + order while it is out of sight — the picker's focus belongs to its + search field, and rows are reached with the arrow keys. + The classes sit on this wrapper, not on the Button: `wrapperClasses` is + twMerged with the button's own `flex`, which drops a conflicting + display and leaves it showing beside the badge. --> + <div + class="col-start-1 row-start-1 invisible opacity-0 transition-[opacity,visibility] duration-150 group-hover:visible group-hover:opacity-100" + > + <Button + unifiedSize="xs" + variant="default" + title={action.title} + startIcon={{ icon: action.icon }} + onClick={action.run} + wrapperClasses="shrink-0" + > + {action.label} + </Button> + </div> + {/if} + {#if badge} + <div + class="col-start-1 row-start-1 transition-[opacity,visibility] duration-150 {action + ? 'group-hover:invisible group-hover:opacity-0' + : ''}" + > + <Badge small color={badge.color}>{badge.label}</Badge> + </div> + {/if} + </div> + {/if} + </div> + {#if actions.length} + <!-- Over the row's end, so a row keeps its layout whether or not it shows them. --> + <div + class="absolute inset-y-0 right-3 flex items-center gap-1" + bind:clientWidth={actionsWidth} + > + {#if mainAction && !done} + <!-- Local, so it waits for the pill to leave but not for a hover. --> + <span data-drill-action in:fade={{ delay: 150, duration: 100 }}> + <Button + unifiedSize="sm" + variant="default" + startIcon={mainAction.icon ? { icon: mainAction.icon } : undefined} + loading={mainAction.loading} + disabled={mainAction.disabled} + onClick={() => mainAction && runAction(mainAction)} + dropdownItems={otherActions.map((a) => ({ + label: a.label, + description: a.hint, + icon: a.icon, + disabled: a.disabled || a.loading, + onClick: () => runAction(a) + }))} + bind:dropdownOpen={actionMenuOpen} + > + {mainAction.label} + </Button> + </span> {/if} </div> - </svelte:element> - <!-- Keyed on the props rather than on this leaf's own badge or action, so a picker - that has either holds the column open on every row: paths then truncate at one - column and the button lands in the same place down the list. --> - {#if leafBadge || leafAction} - <!-- Both sit in one grid cell so they cross-fade in place rather than sitting - side by side or shifting the row as one replaces the other. --> - <div class="shrink-0 min-w-[4.5rem] grid justify-items-end items-center pl-2"> - {#if action} - <!-- `invisible`, not `hidden`: display cannot be transitioned, while - visibility both fades with opacity and keeps the button out of the tab - order while it is out of sight — the picker's focus belongs to its - search field, and rows are reached with the arrow keys. - The classes sit on this wrapper, not on the Button: `wrapperClasses` is - twMerged with the button's own `flex`, which drops a conflicting - display and leaves it showing beside the badge. --> - <div - class="col-start-1 row-start-1 whitespace-nowrap invisible opacity-0 transition-[opacity,visibility] duration-150 group-hover:visible group-hover:opacity-100" - > - <Button - unifiedSize="xs" - variant="default" - title={action.title} - startIcon={{ icon: action.icon }} - onClick={action.run} - wrapperClasses="shrink-0" - > - {action.label} - </Button> - </div> - {/if} - {#if badge} - <div - class="col-start-1 row-start-1 transition-[opacity,visibility] duration-150 {action - ? 'group-hover:invisible group-hover:opacity-0' - : ''}" - > - <Badge small color={badge.color}>{badge.label}</Badge> - </div> - {/if} + {/if} + {#if done} + <!-- SaveButton's success pill, over the row's button and its dropdown chevron. --> + <div + class="absolute inset-y-0 my-auto h-7 right-3 z-10 flex items-center justify-center gap-1.5 px-2 rounded-md text-xs font-medium whitespace-nowrap bg-green-200 dark:bg-green-800 text-green-800 dark:text-green-200" + style={pillWidths[leaf.key] ? `min-width: ${pillWidths[leaf.key]}px` : undefined} + role="status" + transition:fly={{ y: -10, duration: 150 }} + > + <CheckCircle2 size={14} class="shrink-0" /> + {done} </div> {/if} </div> @@ -663,7 +821,11 @@ leaves and ignores the current scope. {#if scope.length > 0 && !isSearching} <button type="button" - class="flex items-center gap-1.5 w-full text-left px-3 py-1 text-xs font-medium font-mono text-secondary bg-surface-secondary/20 hover:bg-surface-hover transition-colors" + class="flex items-center gap-1.5 w-full text-left px-3 py-1 text-xs font-medium {headerChain.every( + (b) => b.plainLabel + ) + ? '' + : 'font-mono'} text-secondary bg-surface-secondary/20 hover:bg-surface-hover transition-colors" onmousedown={(e) => e.preventDefault()} onclick={goUp} title={headerLabel} @@ -737,15 +899,21 @@ leaves and ignores the current scope. role="option" aria-selected={isHl} data-nav-key={entry.key} - class="flex items-center gap-1.5 w-full text-left px-3 py-1.5 text-xs font-medium font-mono text-emphasis transition-colors {isHl - ? 'bg-surface-hover' - : ''}" + class="flex items-center gap-1.5 w-full text-left px-3 py-1.5 text-xs font-medium {entry + .node.plainLabel + ? '' + : 'font-mono'} text-emphasis transition-colors {isHl ? 'bg-surface-hover' : ''}" onmousedown={(e) => e.preventDefault()} onclick={() => drill(entry)} onmouseenter={() => setHoverHighlight(entry.key)} > {@render defaultBranchIcon(entry.node)} <span class="flex-1 truncate">{entry.node.label}</span> + {#if entry.node.badge} + <span class="shrink-0 pl-2 text-xs font-sans font-normal text-secondary" + >{entry.node.badge}</span + > + {/if} {#if entry.node.loading} <Loader2 size={12} class="animate-spin text-tertiary" /> {/if} @@ -760,6 +928,8 @@ leaves and ignores the current scope. <div role="status" class="px-3 py-1.5 text-xs text-tertiary flex items-center gap-2"> <Loader2 size={14} class="animate-spin" /> Loading… </div> + {:else if currentBranch?.note} + <div role="status" class="px-3 py-2 text-xs text-tertiary">{currentBranch.note}</div> {/if} </div> {/if} diff --git a/frontend/src/lib/components/DropdownV2.svelte b/frontend/src/lib/components/DropdownV2.svelte index e9fbf71ab8..c2f56b7d44 100644 --- a/frontend/src/lib/components/DropdownV2.svelte +++ b/frontend/src/lib/components/DropdownV2.svelte @@ -13,7 +13,7 @@ import DropdownV2Inner from './DropdownV2Inner.svelte' import { pointerDownOutside } from '$lib/utils' import { createDropdownMenu, melt, createSync } from '@melt-ui/svelte' - import { overlayPortalTarget } from '$lib/components/common/overlayHost.svelte' + import { overlayPortalTarget, overlayShown } from '$lib/components/common/overlayHost.svelte' import type { MenubarMenuElements } from '@melt-ui/svelte' import ResolveOpen from '$lib/components/common/menu/ResolveOpen.svelte' import Button from '$lib/components/common/button/Button.svelte' @@ -89,6 +89,7 @@ // Overlays belong to the enclosing pane when there is one — see overlayHost. const hostPortal = overlayPortalTarget('body') + const shown = overlayShown() const { elements: { menu: menuEl, item, trigger }, @@ -198,7 +199,7 @@ {/if} </button> -{#if open && !hidePopup} +{#if open && !hidePopup && shown()} <div use:melt={$menuEl} data-menu diff --git a/frontend/src/lib/components/EditableSchemaForm.svelte b/frontend/src/lib/components/EditableSchemaForm.svelte index 9d60dd1866..9cce869320 100644 --- a/frontend/src/lib/components/EditableSchemaForm.svelte +++ b/frontend/src/lib/components/EditableSchemaForm.svelte @@ -197,11 +197,11 @@ properties: Record<string, any> order: string[] | undefined }) { - if (schema.order == undefined && !Array.isArray(schema.order)) { - schema.order = [] - } - let norder = [...schema.order] let properties = Object.keys(schema?.properties ?? {}) + // An absent order means the property order. Writing it out anyway changes the flow on + // mount, and the flow editor's undo then takes that write for an edit and swallows a press. + const currentOrder = Array.isArray(schema.order) ? schema.order : properties + let norder = [...currentOrder] let index = 0 let hasChanged = false for (let k of properties) { @@ -214,7 +214,7 @@ index += 1 } norder = norder.filter((x) => properties.includes(x)) - if (!deepEqual(schema.order, norder)) { + if (!deepEqual(currentOrder, norder)) { schema.order = norder return true } @@ -282,6 +282,11 @@ delete args[oldName] } + // The new key lands last in `properties`, so keep the position through `order`, + // read before the delete since an absent order means the property order. + const order = newSchema.order ?? Object.keys(newSchema.properties ?? {}) + newSchema.order = order.map((x: string) => (x === oldName ? newName : x)) + newSchema.properties[newName] = newSchema.properties[oldName] delete newSchema.properties[oldName] @@ -289,14 +294,6 @@ newSchema.required = newSchema.required?.map((x) => (x === oldName ? newName : x)) } - // Replace the old name with the new name in the order array - if (newSchema.order) { - const index = newSchema.order.indexOf(oldName) - if (index !== -1) { - newSchema.order[index] = newName - } - } - opened = newName schema = newSchema diff --git a/frontend/src/lib/components/Editor.svelte b/frontend/src/lib/components/Editor.svelte index b103e7ddf8..da930c03f4 100644 --- a/frontend/src/lib/components/Editor.svelte +++ b/frontend/src/lib/components/Editor.svelte @@ -5,6 +5,7 @@ </script> <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import { BROWSER } from 'esm-env' import { buildWsUrl } from '$lib/wsUrl' @@ -120,6 +121,7 @@ import { MarkerSeverity } from 'monaco-editor' import { resource, useDebounce, watch } from 'runed' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { registerPendingEditor } from './pendingEditorFlush' const operatingWorkspace = useOperatingWorkspace() // import EditorTheme from './EditorTheme.svelte' @@ -276,6 +278,10 @@ // rather than via getAiChatManager(), which collapses "no session" into the // singleton — the distinction is what tells ⌘L whether a pane exists to open. const sessionScopedChatManager = getContext<AIChatManager | undefined>('aiChatManager') + // Autocomplete in a session's editor follows the session's workspace, not the tab's. + const completionInfo = $derived( + sessionScopedChatManager ? sessionScopedChatManager.aiInfo : $copilotInfo + ) // let graphqlService: MonacoGraphQLAPI | undefined = undefined let fetchedDbSchema: DBSchema | undefined = $state(undefined) @@ -494,6 +500,14 @@ changeChainStart = undefined } + // Same guards as the unmount flush below: only when a keystroke is actually pending. + const unregisterPending = registerPendingEditor({ + flushPendingChanges: () => { + if (editor && timeoutModel !== undefined) flushPendingChanges() + } + }) + onDestroy(unregisterPending) + export function append(code: string): void { if (editor) { const lineCount = editor.getModel()?.getLineCount() || 0 @@ -1008,7 +1022,11 @@ if (autocompletor) { autocompletor.dispose() } - autocompletor = new Autocompletor(editor, scriptLang, { workflowAsCode }) + const session = sessionScopedChatManager + autocompletor = new Autocompletor(editor, scriptLang, { + workflowAsCode, + sessionTarget: session ? () => session.loadedSessionAiTarget : undefined + }) } const outputChannel = { @@ -2082,9 +2100,9 @@ }) $effect(() => { const currentWorkflowAsCode = workflowAsCode - $copilotInfo.enabled && + completionInfo?.enabled && $codeCompletionSessionEnabled && - Autocompletor.isProviderModelSupported($copilotInfo.codeCompletionModel) && + Autocompletor.isProviderModelSupported(completionInfo.codeCompletionModel) && initialized && editor && scriptLang && @@ -2094,7 +2112,7 @@ $copilotInfo.enabled && initialized && editor && untrack(() => editor && addChatHandler(editor)) }) $effect(() => { - ;(!$codeCompletionSessionEnabled || !$copilotInfo.enabled) && autocompletor?.dispose() + ;(!$codeCompletionSessionEnabled || !completionInfo?.enabled) && autocompletor?.dispose() }) $effect(() => { if (yContent && awareness && model && editor) { @@ -2209,7 +2227,7 @@ watch([() => customTsTypesData.current], setTypescriptCustomTypes) </script> -<svelte:window onkeydown={onKeyDown} /> +<HostWindow onkeydown={onKeyDown} /> <EditorTheme /> {#if datatableForMigrations && $operatingWorkspace} <DdlMigrationGuard diff --git a/frontend/src/lib/components/EditorHeader.svelte b/frontend/src/lib/components/EditorHeader.svelte index 6aceb138e8..7c14c330f4 100644 --- a/frontend/src/lib/components/EditorHeader.svelte +++ b/frontend/src/lib/components/EditorHeader.svelte @@ -23,7 +23,8 @@ * item at that same path even though the rename hasn't been deployed). */ savedPath?: string /** Kind of the item being edited; used to label the first breadcrumb segment. */ - kind?: WorkspaceItemKind + /** The agent editor draws its own header. */ + kind?: Exclude<WorkspaceItemKind, 'agent'> /** True when editing a raw app — forwarded into the virtual `currentItem` * so the picker / `editPathFor` can route to `/apps_raw/...`. */ raw_app?: boolean diff --git a/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte b/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte index bddf68fc0d..891b9b298e 100644 --- a/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte +++ b/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte @@ -285,7 +285,7 @@ </script> <div class={classNames('space-y-2', noMargin ? '' : 'mt-2')}> - <ToggleButtonGroup bind:selected={draft.selected} disabled={!isEditable}> + <ToggleButtonGroup bind:selected={draft.selected} disabled={!isEditable} wrap> {#snippet children({ item })} <ToggleButton label="Slack" value="slack" {item} disabled={!isEditable} /> <ToggleButton label="Teams" value="teams" {item} disabled={!isEditable} /> @@ -314,21 +314,25 @@ <div class="flex flex-col gap-6 p-4 rounded-md shadow-sm bg-surface-tertiary"> {#if draft.selected === 'custom'} <div class="flex flex-col gap-1"> - <div class="flex flex-row"> - <ScriptPicker - disabled={!isEditable || (customRequiresEE && !$enterpriseLicense)} - kinds={['script', 'failure']} - allowFlow={true} - bind:scriptPath={draft.custom.path} - bind:itemKind={draft.custom.kind} - allowRefresh={isEditable} - workspace={effectiveWorkspace} - clearable - /> + <div class="flex flex-wrap items-center gap-x-4 gap-y-2"> + <!-- The basis is the narrowest the picker stays usable at; below it the template + button wraps rather than squeezing the select to nothing. --> + <div class="grow basis-72 min-w-0"> + <ScriptPicker + disabled={!isEditable || (customRequiresEE && !$enterpriseLicense)} + kinds={['script', 'failure']} + allowFlow={true} + bind:scriptPath={draft.custom.path} + bind:itemKind={draft.custom.kind} + allowRefresh={isEditable} + workspace={effectiveWorkspace} + clearable + /> + </div> {#if !draft.custom.path} <Button - btnClasses="ml-4 whitespace-nowrap" + btnClasses="whitespace-nowrap" variant="default" size="xs" href={templateHref} diff --git a/frontend/src/lib/components/FilterSearchbar.svelte b/frontend/src/lib/components/FilterSearchbar.svelte index 5b5b583778..46cfdc332e 100644 --- a/frontend/src/lib/components/FilterSearchbar.svelte +++ b/frontend/src/lib/components/FilterSearchbar.svelte @@ -786,6 +786,16 @@ )} {placeholder} onKeyDown={(e) => { + // A shortcut aimed elsewhere (Ctrl/Cmd+K for global search) must not open the dropdown: it + // is portaled above every modal, so it would cover the overlay the shortcut opens. AltGr + // reports Ctrl+Alt, so a character typed with it still opens; so do chords that edit the text. + if (['Control', 'Meta', 'Alt', 'Shift'].includes(e.key)) return + if ( + (e.ctrlKey || e.metaKey) && + !e.altKey && + !['v', 'x', 'z', 'y', 'backspace', 'delete'].includes(e.key.toLowerCase()) + ) + return // In free-text mode the searchbar coexists with a list that owns Arrow/Enter, so opening // the dropdown on a bare navigation key would steal them from an empty box. Typing, click, // or an already-open dropdown still open/keep it. Other searchbars keep opening on any key. diff --git a/frontend/src/lib/components/FirstStepInputs.svelte b/frontend/src/lib/components/FirstStepInputs.svelte index cf936b64f0..d318f03794 100644 --- a/frontend/src/lib/components/FirstStepInputs.svelte +++ b/frontend/src/lib/components/FirstStepInputs.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import { createEventDispatcher, onDestroy, getContext, untrack } from 'svelte' import { getFirstStepSchema } from '$lib/components/flows/flowStore.svelte' import type { FlowEditorContext } from '$lib/components/flows/types' @@ -71,7 +72,7 @@ } </script> -<svelte:window onkeydown={handleKeydown} /> +<HostWindow onkeydown={handleKeydown} /> <div class="h-full"> {#if schema && mod} diff --git a/frontend/src/lib/components/FlowBuilder.svelte b/frontend/src/lib/components/FlowBuilder.svelte index 6d267c8958..6a545423f8 100644 --- a/frontend/src/lib/components/FlowBuilder.svelte +++ b/frontend/src/lib/components/FlowBuilder.svelte @@ -1,4 +1,6 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' + import { overlayHostActive } from '$lib/components/common/overlayHost.svelte' import DeployOnBehalfOfDialog from '$lib/components/itemSettings/DeployOnBehalfOfDialog.svelte' import { deployAsksOnBehalfOf } from '$lib/components/itemSettings/onBehalfOf' import { movesToAnotherOwner } from '$lib/components/itemSettings/inheritedAccess' @@ -22,13 +24,7 @@ linkedAgentToolsVersion, migrateLinkedAgentToolsScope } from '$lib/components/flows/linkedAgentToolsStore.svelte' - import { - enterpriseLicense, - userStore, - userWorkspaces, - usedTriggerKinds, - workspaceStore - } from '$lib/stores' + import { enterpriseLicense, userStore, userWorkspaces, usedTriggerKinds } from '$lib/stores' import { generateRandomString, orderedJsonStringify, @@ -485,9 +481,11 @@ // window handler; Editor/SimpleEditor/TemplateEditor re-broadcast it // (untyped event, hence the manual listener). A step's code editor also // flushes through its `formatAction`, and a redundant flush is a no-op. + const hostActive = overlayHostActive() $effect(() => { - window.addEventListener('wm-monaco-save-shortcut', saveDraft) - return () => window.removeEventListener('wm-monaco-save-shortcut', saveDraft) + const onSaveShortcut = () => hostActive() && saveDraft() + window.addEventListener('wm-monaco-save-shortcut', onSaveShortcut) + return () => window.removeEventListener('wm-monaco-save-shortcut', onSaveShortcut) }) // Materialize a brand-new flow's draft before the session preview loads it by @@ -674,9 +672,7 @@ // 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 ?? '')) ?? - (opWorkspace === $workspaceStore ? $userStore : undefined) + const user = (await getUserExt(opWorkspace ?? '')) ?? operatingUser.in(opWorkspace) const caps = capabilitiesIn( user, $userWorkspaces.find((w) => w.id === opWorkspace) @@ -1189,8 +1185,7 @@ opWorkspace, initialPath, true, - $primaryScheduleStore, - $userStore + $primaryScheduleStore ) } @@ -1722,7 +1717,7 @@ const flowHasChanged = $derived(flowPreviewContent?.flowHasChanged()) </script> -<svelte:window onkeydown={onKeyDown} /> +<HostWindow onkeydown={onKeyDown} /> {@render children?.()} diff --git a/frontend/src/lib/components/FlowLogViewer.svelte b/frontend/src/lib/components/FlowLogViewer.svelte index 1e1c5ade97..2806ade68e 100644 --- a/frontend/src/lib/components/FlowLogViewer.svelte +++ b/frontend/src/lib/components/FlowLogViewer.svelte @@ -739,6 +739,7 @@ id={module.id} {onSelectedIteration} flowJobsSuccess={localModuleStates[module.id]?.flow_jobs_success} + flowJobsLabels={localModuleStates[module.id]?.flow_jobs_labels} flowJobs={localModuleStates[module.id]?.flow_jobs} selected={localModuleStates[module.id]?.selectedForloopIndex ?? 0} selectedManually={localModuleStates[module.id] @@ -748,6 +749,16 @@ </button> {#if module.value.type === 'forloopflow'} {`/${localModuleStates[module.id]?.iteration_total ?? 0}`} + {@const selectedLabel = + localModuleStates[module.id]?.flow_jobs_labels?.[ + localModuleStates[module.id]?.selectedForloopIndex ?? 0 + ]} + {#if selectedLabel} + <span + class="ml-2 font-sans font-normal text-secondary truncate max-w-60" + title={selectedLabel}>{selectedLabel}</span + > + {/if} {/if} </span> {/if} diff --git a/frontend/src/lib/components/FlowLoopIterationPreview.svelte b/frontend/src/lib/components/FlowLoopIterationPreview.svelte index 8da0ee390e..0e05223456 100644 --- a/frontend/src/lib/components/FlowLoopIterationPreview.svelte +++ b/frontend/src/lib/components/FlowLoopIterationPreview.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import { type Job, JobService, type FlowModule, type RestartedFrom } from '$lib/gen' import { Button } from './common' import { createEventDispatcher, getContext } from 'svelte' @@ -153,7 +154,7 @@ }) </script> -<svelte:window onkeydown={onKeyDown} /> +<HostWindow onkeydown={onKeyDown} /> <div class="flex flex-col space-y-2 h-screen bg-surface px-6 py-2 w-full" id="flow-preview-content"> <div class="flex flex-row justify-between w-full items-center gap-x-2"> diff --git a/frontend/src/lib/components/FlowPreviewContent.svelte b/frontend/src/lib/components/FlowPreviewContent.svelte index 67b1dbadff..5880a4ceeb 100644 --- a/frontend/src/lib/components/FlowPreviewContent.svelte +++ b/frontend/src/lib/components/FlowPreviewContent.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import { ApiError, type Job, @@ -28,7 +29,7 @@ RefreshCw, X } from 'lucide-svelte' - import { DynamicInput, sendUserToast, type StateStore } from '$lib/utils' + import { apiErrorMessage, DynamicInput, sendUserToast, type StateStore } from '$lib/utils' import { dfs } from './flows/dfs' import { sliceModules } from './flows/flowStateUtils.svelte' import InputSelectedBadge from './schema/InputSelectedBadge.svelte' @@ -234,7 +235,7 @@ // The chat follows the turn its conversation is still answering rather than // reporting a failed run, so the refusal goes back to it. if (conversationId && e instanceof ApiError && e.status === 409) throw e - sendUserToast('Could not run preview', true, undefined, e.toString()) + sendUserToast('Could not run preview', true, undefined, apiErrorMessage(e)) } schemaFormWithArgPicker?.refreshHistory() return newJobId @@ -369,7 +370,7 @@ } </script> -<svelte:window onkeydown={onKeyDown} /> +<HostWindow onkeydown={onKeyDown} /> <div class="flex flex-col space-y-2 h-screen bg-surface py-2 w-full" id="flow-preview-content"> {#if render} diff --git a/frontend/src/lib/components/FlowStatusViewerInner.svelte b/frontend/src/lib/components/FlowStatusViewerInner.svelte index 308092c1c4..2a875126ad 100644 --- a/frontend/src/lib/components/FlowStatusViewerInner.svelte +++ b/frontend/src/lib/components/FlowStatusViewerInner.svelte @@ -25,7 +25,13 @@ import Tabs from './common/tabs/Tabs.svelte' import { type DurationStatus, type FlowStatusViewerContext, type GraphModuleState } from './graph' import ModuleStatus from './ModuleStatus.svelte' - import { clone, isScriptPreview, msToSec, readFieldsRecursively, truncateRev } from '$lib/utils' + import { + clone, + isScriptPreview, + msToCompactDuration, + readFieldsRecursively, + truncateRev + } from '$lib/utils' import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile' import { appendViewToken } from '$lib/viewToken' import JobArgs from './JobArgs.svelte' @@ -94,6 +100,7 @@ moduleId: string flowJobs: string[] flowJobsSuccess: (boolean | undefined)[] + flowJobsLabels?: (string | null)[] flowJobsDuration: | { started_at?: (string | undefined)[] @@ -108,6 +115,10 @@ innerModule?: FlowModuleValue | undefined render?: boolean selectedNode?: string | undefined + /** Job of the node selected in the root viewer's graph. Nested viewers have no + * selectedNode of their own, so this is how a step inside a subflow, loop or retry + * knows it is selected and must stream its logs. */ + selectedJobId?: string | undefined globalModuleStates: Record<string, GraphModuleState>[] globalDurationStatuses?: Record<string, DurationStatus>[] isSelectedBranch?: boolean @@ -169,6 +180,7 @@ innerModule = undefined, render = true, selectedNode = $bindable(undefined), + selectedJobId = undefined, globalModuleStates, globalDurationStatuses = [], updateRecursiveRefreshFn = undefined, @@ -687,6 +699,7 @@ if (mod.flow_jobs_success || mod.flow_jobs_duration || mod.flow_jobs) { setModuleState(mod.id ?? '', { flow_jobs_success: mod.flow_jobs_success, + flow_jobs_labels: mod.flow_jobs_labels, flow_jobs_duration: mod.flow_jobs_duration, flow_jobs: mod.flow_jobs, iteration_total: mod.iterator?.itered_len ?? mod.flow_jobs?.length @@ -937,16 +950,16 @@ function getAgentActionContent(agentResult: any, actionIndex: number): unknown | undefined { if (!agentResult?.messages || !Array.isArray(agentResult.messages)) return undefined - let agentActionIdx = 0 - for (const m of agentResult.messages) { - if (m.agent_action) { - if (agentActionIdx === actionIndex) { - return m.content - } - agentActionIdx++ - } - } - return undefined + // A background tool's result arrives later as a user message tagged with the action its + // job started: it is not an action of its own, and it answers that one. + const isBackgroundResult = (m: any) => m.role === 'user' && m.agent_action?.type === 'tool_call' + const tagged = agentResult.messages.filter((m: any) => m.agent_action) + const message = tagged.filter((m: any) => !isBackgroundResult(m))[actionIndex] + const jobId = message?.agent_action?.job_id + const result = jobId + ? tagged.find((m: any) => isBackgroundResult(m) && m.agent_action.job_id === jobId) + : undefined + return (result ?? message)?.content } function isSuccess(arg: any): boolean | undefined { @@ -1029,6 +1042,7 @@ started_at: started_at, flow_jobs: mod.flow_jobs, flow_jobs_success: mod.flow_jobs_success, + flow_jobs_labels: mod.flow_jobs_labels, flow_jobs_duration: mod.flow_jobs_duration, iteration_total: mod.iterator?.itered_len, retries: mod?.failed_retries?.length, @@ -1159,6 +1173,7 @@ started_at, flow_jobs: flowJobIds?.flowJobs, flow_jobs_success: flowJobIds?.flowJobsSuccess, + flow_jobs_labels: flowJobIds?.flowJobsLabels, flow_jobs_duration: flowJobIds?.flowJobsDuration, iteration_total: flowJobIds?.length, duration_ms: undefined @@ -1407,6 +1422,11 @@ let noLogs = $derived(graphTabOpen && !isNodeSelected) + // The root viewer's module states hold every nested step, prefixed for subflows. + let effectiveSelectedJobId = $derived( + selectedJobId ?? localModuleStates?.[selectedNode ?? '']?.job_id + ) + /** * Returns a string like "forloopmodid1-{iter1}-forloopmodid2-{iter2}-forloopmodid3-{iter3}-" * that can be used to prefix tool call store keys for nested tool calls. @@ -1450,6 +1470,8 @@ let totalEventsWaiting = $derived( Object.values(suspendStatus?.val ?? {}).reduce((a, b) => a + (b?.nb ?? 0), 0) ) + + let continuedOnError = $derived(job?.flow_status?.continued_on_error ?? []) </script> <JobLoader workspaceOverride={workspaceId} {noLogs} noCode bind:this={jobLoader} /> @@ -1464,6 +1486,36 @@ {:else} <div class="h-8" /> {/if} --> + {#if !isListJob && continuedOnError.length > 0} + <Alert + type="warning" + size="xs" + title="{continuedOnError.length}{continuedOnError.length >= 100 + ? '+' + : ''} step{continuedOnError.length > 1 + ? 's' + : ''} failed, the flow continued because of continue on error" + > + <div class="flex flex-wrap gap-x-3 gap-y-1"> + <!-- A failure raised before its step's job was created (e.g. a branch predicate + error) carries the nil uuid, so entries are keyed by position. --> + {#each continuedOnError as failure, i (i)} + {#if isReplay || failure.job == '00000000-0000-0000-0000-000000000000'} + <span>{failure.id}</span> + {:else} + <a + rel="noreferrer" + target="_blank" + href={appendViewToken(`/run/${failure.job}?workspace=${job?.workspace_id}`)} + > + {failure.id} + <ExternalLink size={12} class="inline-block" /> + </a> + {/if} + {/each} + </div> + </Alert> + {/if} {#if isListJob} {#if render} <div class="w-full border rounded-sm bg-surface p-1 overflow-auto max-h-[90vh]"> @@ -1624,7 +1676,12 @@ }} > <span class="truncate font-mono"> - #{j + 1}: {loopJobId} + #{j + 1}: + {#if flowJobIds?.flowJobsLabels?.[j]} + {flowJobIds.flowJobsLabels[j]} <span class="text-hint">{loopJobId}</span> + {:else} + {loopJobId} + {/if} </span> </Button> {/if} @@ -1668,6 +1725,7 @@ }} {onResultStreamUpdate} graphTabOpen={selected == 'graph' && graphTabOpen} + selectedJobId={effectiveSelectedJobId} isNodeSelected={forloop_selected == loopJobId} toolCallStore={{ getStoredToolCallJob: (storeKey: string) => @@ -1765,6 +1823,7 @@ jobId={failedRetry} {onResultStreamUpdate} graphTabOpen={selected == 'graph' && graphTabOpen} + selectedJobId={effectiveSelectedJobId} isNodeSelected={retry_selected == failedRetry} /> </div> @@ -1801,6 +1860,7 @@ }} {onResultStreamUpdate} graphTabOpen={selected == 'graph' && graphTabOpen} + selectedJobId={effectiveSelectedJobId} isNodeSelected={false} /> {:else if mod.flow_jobs?.length == 0 && mod.job == '00000000-0000-0000-0000-000000000000'} @@ -1827,6 +1887,7 @@ moduleId: mod.id ?? '', flowJobs: mod.flow_jobs, flowJobsSuccess: mod.flow_jobs_success ?? [], + flowJobsLabels: mod.flow_jobs_labels, flowJobsDuration: mod.flow_jobs_duration, length: mod.iterator?.itered_len ?? mod.flow_jobs.length, branchall: job?.raw_flow?.modules?.[i]?.value?.type == 'branchall' @@ -1842,7 +1903,8 @@ }} {onResultStreamUpdate} graphTabOpen={selected == 'graph' && graphTabOpen} - isNodeSelected={localModuleStates?.[selectedNode ?? '']?.job_id == mod.job} + selectedJobId={effectiveSelectedJobId} + isNodeSelected={effectiveSelectedJobId == mod.job} {toolCallStore} showLogsWithResult={['script', 'rawscript'].includes( job.raw_flow?.modules[i]?.value?.type ?? '' @@ -2085,7 +2147,11 @@ wrapperClass={closableDetails ? 'grow min-w-0' : 'shrink-0'} > {#if !hideTimeline} - <Tab value="timeline" label="Timeline" class={closableDetails ? 'px-0' : ''} /> + <Tab + value="timeline" + label="Timeline" + class={closableDetails ? 'px-0' : ''} + /> {/if} <Tab value="node_status" @@ -2271,7 +2337,7 @@ {#if node.duration_ms} <Badge> <Hourglass class="mr-2" size={10} /> - {msToSec(node.duration_ms)} s + {msToCompactDuration(node.duration_ms)} </Badge> {/if} {#if node.job_id && !isReplay} diff --git a/frontend/src/lib/components/FlowTimeline.svelte b/frontend/src/lib/components/FlowTimeline.svelte index a8198c1ade..fd44399e30 100644 --- a/frontend/src/lib/components/FlowTimeline.svelte +++ b/frontend/src/lib/components/FlowTimeline.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { displayDate, msToSec } from '$lib/utils' + import { displayDate, msToCompactDuration } from '$lib/utils' import { Loader2 } from 'lucide-svelte' import TimelineBar from './TimelineBar.svelte' import WaitTimeWarning from './common/waitTimeWarning/WaitTimeWarning.svelte' @@ -167,10 +167,10 @@ </div> {/if} {#if max && min} - <span class="font-mono">{msToSec(max - min, 1)}s</span> + <span class="font-mono">{msToCompactDuration(max - min, 1)}</span> {/if} {#if !max && min}{#if now} - <span class="font-mono">{msToSec(now - min, 1)}s</span> + <span class="font-mono">{msToCompactDuration(now - min, 1)}</span> {/if}<Loader2 size={14} class="animate-spin" />{/if} </div> </div> @@ -198,6 +198,7 @@ id={k} {onSelectedIteration} flowJobsSuccess={localModuleStates[k]?.flow_jobs_success} + flowJobsLabels={localModuleStates[k]?.flow_jobs_labels} flowJobs={localModuleStates[k]?.flow_jobs} selected={localModuleStates[k]?.selectedForloopIndex ?? 0} selectedManually={localModuleStates[k]?.selectedForLoopSetManually ?? false} @@ -213,7 +214,7 @@ </span> {:else if compact && subItems?.[0]?.duration_ms != undefined} <span class="text-2xs text-secondary font-mono"> - {msToSec(subItems[0].duration_ms, 1)}s + {msToCompactDuration(subItems[0].duration_ms, 1)} </span> {/if} </div> @@ -245,6 +246,7 @@ {min} {compact} gray + followedByBar={!!b.started_at} spacerClass="bg-gray-100 dark:bg-gray-800/50 rounded-l-md" started_at={b.created_at} len={waitingLen < 100 ? 0 : waitingLen - 100} @@ -272,7 +274,7 @@ {compact} concat colorClass="bg-purple-400/80" - tooltip={`Waiting for approval — ${msToSec(aw.len, 1)}s`} + tooltip={`Waiting for approval — ${msToCompactDuration(aw.len, 1)}`} started_at={aw.start} len={aw.len} running={aw.running} diff --git a/frontend/src/lib/components/FolderPicker.svelte b/frontend/src/lib/components/FolderPicker.svelte index 0b5bc05897..52ce9cc263 100644 --- a/frontend/src/lib/components/FolderPicker.svelte +++ b/frontend/src/lib/components/FolderPicker.svelte @@ -103,6 +103,10 @@ // switching the owner toggle from "Folder" back to "User". if (!$userStore.folders) $userStore.folders = [] $userStore.folders.push(saved) + // Ownership is checked against `folders_owners` (`isOwner`), which is only + // resent on the next whoami: without this, items saved in the new folder + // keep owner-only actions such as Delete disabled until a reload. + $userStore.folders_owners.push(saved) } } await loadFolders() diff --git a/frontend/src/lib/components/GroupInfo.svelte b/frontend/src/lib/components/GroupInfo.svelte index f1fc758247..e0b1319851 100644 --- a/frontend/src/lib/components/GroupInfo.svelte +++ b/frontend/src/lib/components/GroupInfo.svelte @@ -3,14 +3,18 @@ import { workspaceStore } from '$lib/stores' import Popover from './Popover.svelte' import { untrack } from 'svelte' + import { latestRequest } from '$lib/utils/latestRequest' interface Props { name: string + /** Members are refetched whenever this changes. */ + reloadKey?: unknown } - let { name }: Props = $props() + let { name, reloadKey }: Props = $props() let members: string[] | undefined = $state([]) + const memberLoads = latestRequest() async function loadMembers() { // FAKE DATA FOR TESTING - Set to false to remove all fake data @@ -32,13 +36,16 @@ } } + const isLatest = memberLoads.start() try { - members = (await GroupService.getGroup({ workspace: $workspaceStore!, name })).members + const result = (await GroupService.getGroup({ workspace: $workspaceStore!, name })).members + if (isLatest()) members = result } catch (e) { - members = [] + if (isLatest()) members = [] } } $effect(() => { + reloadKey $workspaceStore && untrack(() => loadMembers()) }) </script> diff --git a/frontend/src/lib/components/HistoricInputs.svelte b/frontend/src/lib/components/HistoricInputs.svelte index 48d1290356..348a810aaf 100644 --- a/frontend/src/lib/components/HistoricInputs.svelte +++ b/frontend/src/lib/components/HistoricInputs.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import { type RunnableType } from '$lib/gen/index.js' import { sendUserToast } from '$lib/utils.js' import RunningJobSchemaPicker from '$lib/components/schema/RunningJobSchemaPicker.svelte' @@ -126,7 +127,7 @@ let jobs = $derived(jobsLoader?.jobs ?? []) </script> -<svelte:window onkeydown={handleKeydown} /> +<HostWindow onkeydown={handleKeydown} /> <div class="h-full max-h-full min-h-0 w-full flex flex-col gap-2 relative"> <div class="grow-0" data-schema-picker> diff --git a/frontend/src/lib/components/InstanceSetting.svelte b/frontend/src/lib/components/InstanceSetting.svelte index 92e31bcf31..c4f6f8b231 100644 --- a/frontend/src/lib/components/InstanceSetting.svelte +++ b/frontend/src/lib/components/InstanceSetting.svelte @@ -141,8 +141,6 @@ }) sendUserToast('Key renewal successful') reloadLicenseKey() - } catch (err) { - throw err } finally { reloadKeyrenewalAttemptInfo() renewing = false diff --git a/frontend/src/lib/components/InstanceSettings.svelte b/frontend/src/lib/components/InstanceSettings.svelte index 135f6898e8..52919b19f9 100644 --- a/frontend/src/lib/components/InstanceSettings.svelte +++ b/frontend/src/lib/components/InstanceSettings.svelte @@ -27,6 +27,7 @@ import { setLicense } from '$lib/enterpriseUtils' import AuthSettings from './AuthSettings.svelte' import oauthConnectRegistry from '$oauth_connect_registry' + import { hasExplicitUrls, normalizeInstanceInput, templatedConnectConfig } from './oauthRegistry' import InstanceSetting from './InstanceSetting.svelte' import { writable, type Writable } from 'svelte/store' import { ExternalLink, Loader2 } from 'lucide-svelte' @@ -319,22 +320,19 @@ .map(([name, cfg]) => [name, (cfg as any).connect_config_template]) ) - function normalizeInstanceInput(tmpl: any, raw: string): string { - let v = (raw ?? '').replace(/\s/g, '') - if (tmpl.strip_suffix) { - // accept a full host/URL or a bare name -> reduce to the bare instance - v = v.replace(/^https?:\/\//, '').replace(/\/.*$/, '') - if (v.endsWith(tmpl.strip_suffix)) { - v = v.slice(0, -tmpl.strip_suffix.length) - } - } - return v - } - // Build each per-instance provider's connect_config from the admin-entered // instance name + its registry template (substituting {instance} into the // URLs). Replaces the old per-provider setup functions. function setupTemplatedOauthUrls() { + // An entry with every way turned off (an empty grant list, unlike an absent one, + // which means authorization code) does nothing, so it is not saved. One stored that + // way is kept: authorization code resources still refresh through it. + const isEmpty = (e: any) => Array.isArray(e?.grant_types) && e.grant_types.length === 0 + for (const [name, entry] of Object.entries(oauths ?? {})) { + if (isEmpty(entry) && !isEmpty(initialOauths?.[name])) { + delete oauths[name] + } + } // 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. @@ -346,19 +344,10 @@ const key = tmpl.extra_params_key ?? 'instance' const v = normalizeInstanceInput(tmpl, instanceInputs[name] ?? '') instanceInputs[name] = v - if (oauths[name].connect_config?.extra_params?.[key] === v) continue - oauths[name].connect_config = { - scopes: tmpl.scopes ?? [], - // CC-only templated providers have no auth_url; store an empty string - // (not omitted) so the instance-config parser still types the entry. - // The backend treats an empty auth_url as the unused placeholder for - // the client-credentials grant. - auth_url: tmpl.auth_url ? tmpl.auth_url.replaceAll('{instance}', v) : '', - token_url: tmpl.token_url.replaceAll('{instance}', v), - req_body_auth: tmpl.req_body_auth ?? false, - extra_params: { [key]: v }, - extra_params_callback: {} - } + const cc = oauths[name].connect_config + if (cc?.extra_params?.[key] === v) continue + if (hasExplicitUrls(tmpl, v, cc)) continue + oauths[name].connect_config = templatedConnectConfig(tmpl, v) } } @@ -376,8 +365,6 @@ sendingStats = true await SettingService.sendStats() sendUserToast('Usage sent') - } catch (err) { - throw err } finally { sendingStats = false } @@ -399,8 +386,6 @@ document.body.removeChild(a) URL.revokeObjectURL(url) sendUserToast('Telemetry data downloaded') - } catch (err) { - throw err } finally { downloadingStats = false } @@ -1189,6 +1174,7 @@ {:else if category == 'Auth/OAuth/SAML'} <AuthSettings bind:oauths + savedOauths={initialOauths} bind:instanceInputs bind:requirePreexistingUserForOauth baseUrl={$values?.base_url} diff --git a/frontend/src/lib/components/JobLoader.svelte b/frontend/src/lib/components/JobLoader.svelte index fa812cc6e4..2a15f27022 100644 --- a/frontend/src/lib/components/JobLoader.svelte +++ b/frontend/src/lib/components/JobLoader.svelte @@ -972,10 +972,10 @@ return } let nextIteration = 50 - if (syncIteration > ITERATIONS_BEFORE_SLOW_REFRESH) { - nextIteration = 500 - } else if (syncIteration > ITERATIONS_BEFORE_SUPER_SLOW_REFRESH) { + if (syncIteration > ITERATIONS_BEFORE_SUPER_SLOW_REFRESH) { nextIteration = 2000 + } else if (syncIteration > ITERATIONS_BEFORE_SLOW_REFRESH) { + nextIteration = 500 } setTimeout(() => syncer(id, callbacks), nextIteration) } diff --git a/frontend/src/lib/components/JobStatus.svelte b/frontend/src/lib/components/JobStatus.svelte index 30fd5f0a27..a905f32874 100644 --- a/frontend/src/lib/components/JobStatus.svelte +++ b/frontend/src/lib/components/JobStatus.svelte @@ -17,20 +17,42 @@ } let { job, large = false }: Props = $props() + + let continuedOnError = $derived(job?.flow_status?.continued_on_error ?? []) </script> +{#snippet continuedOnErrorBadge()} + {#if continuedOnError.length > 0} + <Badge + {large} + color="orange" + title="Failed steps skipped by continue on error: {continuedOnError + .map((f) => f.id) + .join(', ')}" + > + {continuedOnError.length}{continuedOnError.length >= 100 ? '+' : ''} failed step{continuedOnError.length > + 1 + ? 's' + : ''} continued + </Badge> + {/if} +{/snippet} + {#if job && 'success' in job && job.success} - <Badge {large} color="green"> - Successfully ran in {msToReadableTime(job.duration_ms)} - {job.is_skipped ? '(Skipped)' : ''} - {#if job.self_wait_time_ms || job.aggregate_wait_time_ms} - <WaitTimeWarning - self_wait_time_ms={job.self_wait_time_ms} - aggregate_wait_time_ms={job.aggregate_wait_time_ms} - variant="alert" - /> - {/if} - </Badge> + <div class="flex flex-row flex-wrap gap-1 items-center"> + <Badge {large} color="green"> + Successfully ran in {msToReadableTime(job.duration_ms)} + {job.is_skipped ? '(Skipped)' : ''} + {#if job.self_wait_time_ms || job.aggregate_wait_time_ms} + <WaitTimeWarning + self_wait_time_ms={job.self_wait_time_ms} + aggregate_wait_time_ms={job.aggregate_wait_time_ms} + variant="alert" + /> + {/if} + </Badge> + {@render continuedOnErrorBadge()} + </div> {:else if job && 'success' in job && job.resolved} <Badge {large} color="orange" title={job.resolution_note}> <!-- `resolved_by` is absent both for an automatic resolution and for a manual one @@ -69,13 +91,14 @@ </Badge> </div> {:else if job && 'running' in job && job.running} - <div> + <div class="flex flex-row flex-wrap gap-1 items-center"> <Badge {large} color="yellow"> Running {#if job.flow_status} ({(job.flow_status?.step ?? 0) + 1} of {job.raw_flow?.modules?.length ?? '?'}) {/if} </Badge> + {@render continuedOnErrorBadge()} </div> {:else if job && 'running' in job && 'scheduled_for' in job && job.scheduled_for && forLater(job.scheduled_for)} <div> diff --git a/frontend/src/lib/components/JsonInputs.svelte b/frontend/src/lib/components/JsonInputs.svelte index 546ab36069..2f86fc4850 100644 --- a/frontend/src/lib/components/JsonInputs.svelte +++ b/frontend/src/lib/components/JsonInputs.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import SimpleEditor from '$lib/components/SimpleEditor.svelte' import { createEventDispatcher, onDestroy, untrack } from 'svelte' import { setEditorUnparseable } from './pendingEditorFlush' @@ -106,7 +107,7 @@ } </script> -<svelte:window onkeydown={handleKeydown} /> +<HostWindow onkeydown={handleKeydown} /> <!-- Add a hidden button that can receive focus --> <button bind:this={focusTrap} class="sr-only" tabindex="-1" aria-hidden="true">Focus trap</button> diff --git a/frontend/src/lib/components/MarkdownCodeBlock.svelte b/frontend/src/lib/components/MarkdownCodeBlock.svelte index 46ba73c281..446bfc4bf1 100644 --- a/frontend/src/lib/components/MarkdownCodeBlock.svelte +++ b/frontend/src/lib/components/MarkdownCodeBlock.svelte @@ -30,13 +30,20 @@ // markdown surfaces don't execute mermaid — the chat opts in. renderMermaid = false, // Draw diagrams in the light theme whatever the app's theme (printing). - lightMermaid = false + lightMermaid = false, + // Render ```wm-display blocks (charts, tables) through DisplayResult. The fence only + // admits inert kinds (`fenceSchema`), so any surface may opt in. + renderDisplay = false, + // Draw display blocks for paper: plain tables rather than the paginated grid. + staticDisplay = false }: { showApplyButton?: boolean onApplyCode?: () => void applyButtonIcon?: typeof ClipboardCopy renderMermaid?: boolean lightMermaid?: boolean + renderDisplay?: boolean + staticDisplay?: boolean } = $props() const astNode = getAstNode() @@ -124,7 +131,10 @@ ) let language = $derived( - (astNode.current.children?.[0]?.properties?.class as string | undefined)?.split('-')[1] + (astNode.current.children?.[0]?.properties?.class as string | undefined) + ?.split(' ') + .find((c) => c.startsWith('language-')) + ?.slice('language-'.length) ) let smartLang = $derived(getSmartLang(language)) @@ -135,6 +145,14 @@ <div class="relative w-full bg-surface-secondary rounded-md overflow-hidden"> {#if renderMermaid && language === 'mermaid'} <MermaidDisplay code={code ?? ''} forceLight={lightMermaid} /> + {:else if renderDisplay && language === 'wm-display'} + <!-- Keep this import lazy: DisplayResult's imports reach back into the chat, and a static + import here left Home's session composer stuck on its loading placeholder. --> + {#await import('./display/DisplayFence.svelte')} + <div data-display-pending="true"></div> + {:then { default: DisplayFence }} + <DisplayFence code={code ?? ''} staticRender={staticDisplay} /> + {/await} {:else} <HighlightCode className="px-3 py-2.5 !text-xs" diff --git a/frontend/src/lib/components/NavBreadcrumb.svelte b/frontend/src/lib/components/NavBreadcrumb.svelte index 6d776e6a84..019c94083c 100644 --- a/frontend/src/lib/components/NavBreadcrumb.svelte +++ b/frontend/src/lib/components/NavBreadcrumb.svelte @@ -55,6 +55,7 @@ not this component) — so the lead can run the whole line. section, afterName, actingWorkspaceId, + onPickWorkspace, nameOnly = false, stage = BAR_STAGES[0], caps = {}, @@ -68,11 +69,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 + /** See `PageHeaderContent.onPickWorkspace`. */ + onPickWorkspace?: (id: string, landOnHome: boolean) => 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. */ + /** Even the name at its last floor does not fit: the folders above it truncate too, and a + * section's own widget may shrink. */ scopesGive?: boolean /** Filled in for the bar to choose a stage with; left undefined, nothing is measured. */ measures?: TrailMeasures @@ -95,6 +99,10 @@ not this component) — so the lead can run the whole line. const found = navPageFor(page.url.pathname) return found?.path === '/' ? undefined : found }) + // A page with panes names the pane, not itself, but its picker still files them under it. + const pickerPagePath = $derived( + routePage?.path ?? (section?.subpages ? navPageFor(page.url.pathname)?.path : undefined) + ) /** One look for every segment, whichever picker it opens. */ const SEGMENT = @@ -283,8 +291,9 @@ not this component) — so the lead can run the whole line. {#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} + item. A session's preview band has the tab's own picker for that, so it shows this one only + on a page with panes, whose name here is the pane's. --> + {#if !section?.noNavPicker && (!nameOnly || (section?.subpages && !item))} {#if measure} <span class="flex items-center h-9 px-1.5 shrink-0"> <ChevronDown size={ICON} class="flex-shrink-0" /> @@ -292,9 +301,10 @@ not this component) — so the lead can run the whole line. {:else} <BreadcrumbNavPicker {item} - pagePath={routePage?.path} + pagePath={pickerPagePath} artifacts={section?.navArtifacts} {actingWorkspaceId} + subpages={item ? undefined : section?.subpages} iconSize={ICON} /> {/if} @@ -339,6 +349,7 @@ not this component) — so the lead can run the whole line. <WorkspacePickerBody item={menuItem} collapseFamilies={actingWorkspaceId != undefined} + interceptSwitch={onPickWorkspace} closeMenu={() => workspaceMenu?.close()} /> {/snippet} @@ -517,27 +528,37 @@ not this component) — so the lead can run the whole line. {: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> + {#if section.parentHref && !measure} + <a href={section.parentHref} class={twMerge(SEGMENT, LEAD, 'shrink-[999]')}> + <span class="truncate">{section.parent}</span> + </a> + {:else} + <span + class={twMerge(SEGMENT, LEAD, 'shrink-[999] hover:bg-transparent hover:text-secondary')} + > + <span class="truncate">{section.parent}</span> + </span> + {/if} {@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. --> + <!-- A section's own widget lays out as a row: its title, and whatever belongs with it. It keeps + its width, which the measured copies reserve, until even the last stage leaves it too + little (`scopesGive`). Read while the row squeezes it, the width would let a wider stage + fit, and the bar would flip between the two every frame. --> <span class={twMerge( SEGMENT, LAST, 'hover:bg-transparent hover:text-emphasis', - section.content ? '' : 'shrink-0' + section.content && scopesGive ? '' : 'shrink-0' )} aria-current={measure ? undefined : 'page'} bind:clientWidth={ - () => sectionContentWidth, (w) => !measure && section.content && (sectionContentWidth = w) + () => sectionContentWidth, + (w) => !measure && section.content && !scopesGive && (sectionContentWidth = w) } > <!-- A plain label is the page's name, so it truncates the way an item's name does, in diff --git a/frontend/src/lib/components/ObjectStoreConfigSettings.svelte b/frontend/src/lib/components/ObjectStoreConfigSettings.svelte index 9ddd7f7fdc..eab901f92f 100644 --- a/frontend/src/lib/components/ObjectStoreConfigSettings.svelte +++ b/frontend/src/lib/components/ObjectStoreConfigSettings.svelte @@ -51,6 +51,8 @@ import Label from './Label.svelte' import TextInput from './text_input/TextInput.svelte' + type BucketType = ObjectStoreConfig['type'] + interface Props { bucket_config?: ObjectStoreConfig | undefined /** Whether this is the instance object store. Everything that reaches out to a store @@ -74,6 +76,40 @@ let loading = $state(false) + // Each storage type's config, so switching tabs (e.g. S3 -> Azure -> S3) restores + // what was entered or loaded: resetting it to an empty config would wipe a saved + // bucket, and saving would then persist the empty value. + let bucketConfigByType = $state<Partial<Record<BucketType, ObjectStoreConfig>>>({}) + + function defaultBucketConfig(type: BucketType): ObjectStoreConfig { + switch (type) { + case 'S3': + return { + type: 'S3', + bucket: '', + region: '', + access_key: '', + secret_key: '', + endpoint: '', + allow_http: true + } + case 'Azure': + return { + type: 'Azure', + accountName: '', + containerName: '', + useSSL: false, + tenantId: '', + clientId: '', + accessKey: '' + } + case 'AwsOidc': + return { type: 'AwsOidc', bucket: '', region: '', roleArn: '' } + case 'Gcs': + return { type: 'Gcs', bucket: '', serviceAccountKey: {} } + } + } + async function testConnection() { loading = true try { @@ -278,19 +314,8 @@ options={{ right: bucket_config ? '' : 'set object store' }} checked={Boolean(bucket_config)} on:change={(e) => { - if (e.detail) { - bucket_config = { - type: 'S3', - bucket: '', - region: '', - access_key: '', - secret_key: '', - endpoint: '', - allow_http: true - } - } else { - bucket_config = undefined - } + bucketConfigByType = {} + bucket_config = e.detail ? defaultBucketConfig('S3') : undefined }} /> </div> @@ -470,40 +495,12 @@ <Tabs selected={bucket_config?.type ?? 'S3'} on:selected={(e) => { - if (e.detail === 'S3' && bucket_config?.type !== 'S3') { - bucket_config = { - type: 'S3', - bucket: '', - region: '', - access_key: '', - secret_key: '', - endpoint: '', - allow_http: true - } - } else if (e.detail === 'Azure' && bucket_config?.type !== 'Azure') { - bucket_config = { - type: 'Azure', - accountName: '', - containerName: '', - useSSL: false, - tenantId: '', - clientId: '', - accessKey: '' - } - } else if (e.detail === 'Gcs' && bucket_config?.type !== 'Gcs') { - bucket_config = { - type: 'Gcs', - bucket: '', - serviceAccountKey: {} - } - } else if (e.detail === 'AwsOidc' && bucket_config?.type !== 'AwsOidc') { - bucket_config = { - type: 'AwsOidc', - bucket: '', - region: '', - roleArn: '' - } + const target = e.detail as BucketType + if (!bucket_config || bucket_config.type === target) { + return } + bucketConfigByType[bucket_config.type] = bucket_config + bucket_config = bucketConfigByType[target] ?? defaultBucketConfig(target) }} > <Tab value="S3" label="S3" /> diff --git a/frontend/src/lib/components/PageHeaderBar.svelte b/frontend/src/lib/components/PageHeaderBar.svelte index 1646bb9a9f..e7254172b5 100644 --- a/frontend/src/lib/components/PageHeaderBar.svelte +++ b/frontend/src/lib/components/PageHeaderBar.svelte @@ -318,6 +318,7 @@ The row's height matches the sidebar's own header row, so the two read as one ba nameOnly={navHidden} afterName={content?.afterName} actingWorkspaceId={content?.actingWorkspaceId} + onPickWorkspace={content?.onPickWorkspace} /> </ContextBridge> {/key} diff --git a/frontend/src/lib/components/PageHeaderContent.svelte b/frontend/src/lib/components/PageHeaderContent.svelte index 94450cf9ab..8bd533f4bf 100644 --- a/frontend/src/lib/components/PageHeaderContent.svelte +++ b/frontend/src/lib/components/PageHeaderContent.svelte @@ -3,7 +3,8 @@ Fills the layout's page header from the route that mounts it: the breadcrumb (an item's path, or a section name for a list) and the page's own buttons. Renders nothing itself. -Only a route page mounts this. An editor nested in a session pane or a drawer must not take over +Only a route page mounts this, or the sessions view while its route is open: the layout keeps +that view mounted on every page. An editor nested in a session pane or a drawer must not take over the header, so nesting is decided by the caller rather than guessed from context. --> <script lang="ts"> @@ -27,6 +28,7 @@ the header, so nesting is decided by the caller rather than guessed from context separator, contexts, actingWorkspaceId, + onPickWorkspace, barRightInset }: PageHeaderContent = $props() @@ -48,6 +50,7 @@ the header, so nesting is decided by the caller rather than guessed from context separator, contexts, actingWorkspaceId, + onPickWorkspace, barRightInset })) return () => pageHeader.release(id) diff --git a/frontend/src/lib/components/Path.svelte b/frontend/src/lib/components/Path.svelte index 68604a4a91..06d8a809ad 100644 --- a/frontend/src/lib/components/Path.svelte +++ b/frontend/src/lib/components/Path.svelte @@ -525,7 +525,9 @@ setDirty() meta.ownerKind = v if (v === 'folder') { - meta.owner = folders?.[0]?.name ?? '' + // Prefer a folder the user can write to: a read-only one cannot + // be picked in the list and saving in it is refused. + meta.owner = (folders.find((f) => f.write) ?? folders[0])?.name ?? '' } else { // 'group' is unreachable here (Select only offers user/folder) // but validateName still accepts it for forward-compat. diff --git a/frontend/src/lib/components/Portal.svelte b/frontend/src/lib/components/Portal.svelte index 801188de2e..6a1cc6e698 100644 --- a/frontend/src/lib/components/Portal.svelte +++ b/frontend/src/lib/components/Portal.svelte @@ -49,6 +49,8 @@ </script> <script> + import { overlayShown } from '$lib/components/common/overlayHost.svelte' + /** * @typedef {Object} Props * @property { HTMLElement|string} [target] - DOM Element or CSS Selector @@ -59,8 +61,12 @@ /** @type {Props} */ let { target = 'body', name = undefined, class: clazz = undefined, children } = $props() + + const shown = overlayShown() </script> -<div use:portal={{ target, name }} hidden class={clazz}> - {@render children?.()} -</div> +{#if shown()} + <div use:portal={{ target, name }} hidden class={clazz}> + {@render children?.()} + </div> +{/if} diff --git a/frontend/src/lib/components/ResourceEditor.svelte b/frontend/src/lib/components/ResourceEditor.svelte index 3e842e040f..b2a2ae6ab6 100644 --- a/frontend/src/lib/components/ResourceEditor.svelte +++ b/frontend/src/lib/components/ResourceEditor.svelte @@ -658,20 +658,23 @@ 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 + // An agent keeps the identity its value names, else the deployed one, since its draft + // never carries 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 agentObo = + fetched?.resource_type === 'ai_agent' + ? (s.args?.on_behalf_of ?? (fetched.value as any)?.on_behalf_of) + : undefined await ResourceService.updateResource({ workspace: ws, path: ini.path, requestBody: { path: s.path, - value: s.args, + value: agentObo ? { ...s.args, on_behalf_of: agentObo } : s.args, description: s.description, labels: s.labels, ws_specific: s.wsSpecific, - preserve_on_behalf_of: keepAgentObo ? true : undefined + preserve_on_behalf_of: agentObo ? true : undefined } }) if (fetched?.resource_type === 'json_schema') { diff --git a/frontend/src/lib/components/ResourceForm.svelte b/frontend/src/lib/components/ResourceForm.svelte index 78c71d00d9..2a23d593d0 100644 --- a/frontend/src/lib/components/ResourceForm.svelte +++ b/frontend/src/lib/components/ResourceForm.svelte @@ -9,14 +9,14 @@ import { Trash2 } from 'lucide-svelte' import Path from './Path.svelte' import LabelsInput from './LabelsInput.svelte' - import { type UserExt } from '$lib/stores' + import { enterpriseLicense, type UserExt } from '$lib/stores' import SchemaForm from './SchemaForm.svelte' import SimpleEditor from './SimpleEditor.svelte' import FilesetEditor from './FilesetEditor.svelte' import Toggle from './Toggle.svelte' import TestConnection from './TestConnection.svelte' import TestAiKey from './copilot/TestAIKey.svelte' - import { aiResourceProvider } from './copilot/aiResourceProvider' + import { aiResourceProvider, isTokenVertexResource } from './copilot/aiResourceProvider' import { copilotInfo } from '$lib/aiStore' import GfmMarkdown from './GfmMarkdown.svelte' import TestTriggerConnection from './triggers/TestTriggerConnection.svelte' @@ -95,7 +95,7 @@ }: Props = $props() let ws = $derived(workspace ?? $operatingWorkspace) - let aiProvider = $derived(aiResourceProvider(resource_type)) + let aiProvider = $derived(aiResourceProvider(resource_type, args)) let rawCode: string | undefined = $state(undefined) let textFileContent: string = $state('') @@ -362,6 +362,13 @@ {/if} {/if} </div> + {#if $enterpriseLicense && !showReference && isTokenVertexResource(resource_type, args)} + <p class="text-xs text-secondary"> + To stop storing and refreshing an access token, use a + <span class="font-mono">vertex_ai_federated</span> resource instead: Windmill authenticates to + Vertex AI through Workload Identity Federation and refreshes the token itself. + </p> + {/if} <div> <ResourceValueReference diff --git a/frontend/src/lib/components/RunsPage.svelte b/frontend/src/lib/components/RunsPage.svelte index 95c9e5677f..4711867f8b 100644 --- a/frontend/src/lib/components/RunsPage.svelte +++ b/frontend/src/lib/components/RunsPage.svelte @@ -405,9 +405,7 @@ : undefined, // isFlowStep: jobKindsCat != 'all' ? false : undefined, hasNullParent: - filters.val.path != undefined || - filters.val.path != undefined || - filters.val.job_kinds != 'all' + filters.val.path != undefined || filters.val.folder || filters.val.job_kinds != 'all' ? true : undefined, label: filters.val.label || undefined, @@ -562,7 +560,7 @@ body: JSON.stringify(body) } ) - await new Promise(async (resolve) => { + { const reader = response?.body?.pipeThrough(new TextDecoderStream()).getReader() let reRanUuids: string[] = [] if (reader) { @@ -610,8 +608,7 @@ } } } - resolve(undefined) - }) + } selectedIds = [] // Opened from the table's "Run again", the options are done; left open, the next selection diff --git a/frontend/src/lib/components/SavedInputsPicker.svelte b/frontend/src/lib/components/SavedInputsPicker.svelte index 4749c6745f..dcc23950f5 100644 --- a/frontend/src/lib/components/SavedInputsPicker.svelte +++ b/frontend/src/lib/components/SavedInputsPicker.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import { Button } from '$lib/components/common' import { InputService, type Input, type RunnableType } from '$lib/gen/index.js' import { userStore } from '$lib/stores.js' @@ -162,7 +163,7 @@ function handleKeydown(event: KeyboardEvent) { if (event.key === 'Escape' && isEditing) { - setEditing(null) + setEditing(null, true) event.stopPropagation() event.preventDefault() } else if (event.key === 'Escape' && selectedInput) { @@ -172,15 +173,24 @@ } if (event.key === 'Enter' && isEditing) { + const session = editSession updateInput(isEditing).then(() => { - setEditing(null) + // a rename opened while this one was saving, even of the same row, stays open + if (editSession === session) setEditing(null) }) event.stopPropagation() event.preventDefault() } } - function setEditing(input: EditableInput | null) { + // The rename field edits the listed input itself, so a cancelled rename must put its name back, + // unless its save is in flight: that has already sent the new name. + let nameBeforeEdit = '' + let editSession = 0 + function setEditing(input: EditableInput | null, cancel = false) { + editSession++ + if (cancel && isEditing && !isEditing.isSaving) isEditing.name = nameBeforeEdit + nameBeforeEdit = input?.name ?? '' isEditing = input dispatch('isEditing', !!input) } @@ -218,7 +228,7 @@ }) </script> -<svelte:window onkeydown={handleKeydown} /> +<HostWindow onkeydown={handleKeydown} /> <div class="w-full flex flex-col gap-1 h-full overflow-y-auto pb-4"> {#if !noButton} @@ -331,7 +341,7 @@ updateInput(isEditing) setEditing(null) } else { - setEditing(item) + setEditing(item, true) } }} startIcon={{ icon: Pencil }} diff --git a/frontend/src/lib/components/SavedInputsV2.svelte b/frontend/src/lib/components/SavedInputsV2.svelte index a023f33c45..50924cbd19 100644 --- a/frontend/src/lib/components/SavedInputsV2.svelte +++ b/frontend/src/lib/components/SavedInputsV2.svelte @@ -47,6 +47,8 @@ let historicInputs: HistoricInputs | undefined = $state(undefined) let runnableId = $derived(scriptHash || scriptPath || flowPath || undefined) + // The runs page filters by path, and on an older version of a script runnableId is a hash. + let runsPath = $derived(scriptPath || flowPath || '') let runnableType: RunnableType | undefined = $derived( scriptHash ? 'ScriptHash' : scriptPath ? 'ScriptPath' : flowPath ? 'FlowPath' : undefined @@ -158,7 +160,7 @@ <Button unifiedSize="sm" endIcon={{ icon: ExternalLink }} - href={`/runs/${runnableId}`} + href={`/runs/${runsPath}`} target="_blank" > All runs diff --git a/frontend/src/lib/components/SchemaForm.svelte b/frontend/src/lib/components/SchemaForm.svelte index 9aec06f832..7be8455d88 100644 --- a/frontend/src/lib/components/SchemaForm.svelte +++ b/frontend/src/lib/components/SchemaForm.svelte @@ -79,6 +79,8 @@ | undefined workspace?: string | undefined chatInputEnabled?: boolean + /** See ArgInput's `fillNullableDefault`; nested forms inherit their parent input's value. */ + fillNullableDefault?: boolean actions?: import('svelte').Snippet<[{ item: { id: string; value: string } }]> | undefined } @@ -123,6 +125,7 @@ computeS3ForceViewerPolicies = undefined, workspace = undefined, chatInputEnabled = false, + fillNullableDefault = true, actions: actions_render = undefined }: Props = $props() @@ -363,6 +366,7 @@ simpleTooltip={schemaFieldTooltip[argName]} {onlyMaskPassword} nullable={formerProperty?.nullable} + {fillNullableDefault} title={formerProperty?.title} placeholder={formerProperty?.placeholder} orderEditable={dndConfig != undefined} @@ -444,6 +448,7 @@ simpleTooltipWarning={argName in schemaFieldWarnings} {onlyMaskPassword} nullable={prop?.nullable} + {fillNullableDefault} title={prop?.title} placeholder={prop?.placeholder} orderEditable={dndConfig != undefined} diff --git a/frontend/src/lib/components/ScriptBuilder.svelte b/frontend/src/lib/components/ScriptBuilder.svelte index 3408c97646..29c5b79797 100644 --- a/frontend/src/lib/components/ScriptBuilder.svelte +++ b/frontend/src/lib/components/ScriptBuilder.svelte @@ -1,4 +1,6 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' + import { overlayHostActive } from '$lib/components/common/overlayHost.svelte' import DeployOnBehalfOfDialog from '$lib/components/itemSettings/DeployOnBehalfOfDialog.svelte' import { deployAsksOnBehalfOf } from '$lib/components/itemSettings/onBehalfOf' import { movesToAnotherOwner } from '$lib/components/itemSettings/inheritedAccess' @@ -483,8 +485,7 @@ opWorkspace, initialPath, false, - $primaryScheduleStore, - $userStore + $primaryScheduleStore ) } @@ -1321,6 +1322,7 @@ return dropdownItems.length > 0 ? dropdownItems : undefined } + const hostActive = overlayHostActive() function onKeyDown(event: KeyboardEvent) { // Lowercased so Caps Lock (which yields `S`) still saves. Shift excluded: // Ctrl+Shift+S must reach the browser/OS. @@ -1338,8 +1340,9 @@ // window handler above; Editor/SimpleEditor/TemplateEditor re-broadcast it // (untyped event, hence the manual listener). $effect(() => { - window.addEventListener('wm-monaco-save-shortcut', saveDraft) - return () => window.removeEventListener('wm-monaco-save-shortcut', saveDraft) + const onSaveShortcut = () => hostActive() && saveDraft() + window.addEventListener('wm-monaco-save-shortcut', onSaveShortcut) + return () => window.removeEventListener('wm-monaco-save-shortcut', onSaveShortcut) }) let path: Path | undefined = $state(undefined) @@ -1549,7 +1552,7 @@ } </script> -<svelte:window onkeydown={onKeyDown} /> +<HostWindow onkeydown={onKeyDown} /> {@render children?.()} <DeployOnBehalfOfDialog diff --git a/frontend/src/lib/components/ScriptEditor.svelte b/frontend/src/lib/components/ScriptEditor.svelte index 3079089828..95d41a182f 100644 --- a/frontend/src/lib/components/ScriptEditor.svelte +++ b/frontend/src/lib/components/ScriptEditor.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import { MultiplayerConnection } from '$lib/multiplayerConnection' import { paneMinPercent } from '$lib/utils/splitpaneSizing' import { processSecretArgs } from './secretArgUtils' @@ -1870,7 +1871,7 @@ bind:job={testJob} /> -<svelte:window onkeydown={onKeyDown} /> +<HostWindow onkeydown={onKeyDown} /> <!-- Standalone triggerable registration for the script editor --> <div diff --git a/frontend/src/lib/components/TimelineBar.svelte b/frontend/src/lib/components/TimelineBar.svelte index 55a502ef9a..43c72a9c8b 100644 --- a/frontend/src/lib/components/TimelineBar.svelte +++ b/frontend/src/lib/components/TimelineBar.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { msToSec } from '$lib/utils' + import { msToCompactDuration, msToReadableTime } from '$lib/utils' import { ExternalLink } from 'lucide-svelte' import Popover from './Popover.svelte' @@ -20,6 +20,8 @@ tooltip?: string /** A thin bar with no duration inside it: the caller shows the duration elsewhere. */ compact?: boolean + /** Another bar starts where this one ends, so a narrow bar's outside label would collide with its label. */ + followedByBar?: boolean } let { @@ -35,7 +37,8 @@ spacerClass = '', colorClass = undefined, tooltip = undefined, - compact = false + compact = false, + followedByBar = false }: Props = $props() </script> @@ -73,15 +76,16 @@ {@const narrow = len / total < 0.09} {@const endPos = started_at != undefined && min != undefined ? (started_at - min + len) / total : 1} - {@const nearStart = endPos < 0.15} - <span - class={narrow - ? nearStart - ? 'absolute left-full ml-2 text-primary font-mono' - : 'absolute right-full mr-1 text-primary font-mono' - : 'font-mono'} - >{#if len}{msToSec(len, 1)}s{/if}</span - > + {#if !(narrow && followedByBar)} + <span + title={msToReadableTime(len, 1)} + class={narrow + ? endPos > 0.85 + ? 'absolute right-full mr-1 text-primary font-mono' + : 'absolute left-full ml-2 text-primary font-mono' + : 'font-mono truncate px-1'}>{msToCompactDuration(len, 1)}</span + > + {/if} {/if} </Popover> {/if} diff --git a/frontend/src/lib/components/VariableEditor.svelte b/frontend/src/lib/components/VariableEditor.svelte index 6095419f6c..765f3be565 100644 --- a/frontend/src/lib/components/VariableEditor.svelte +++ b/frontend/src/lib/components/VariableEditor.svelte @@ -458,13 +458,10 @@ path: ini.path, requestBody: { path: ini.path != s.path ? s.path : undefined, - // An empty value keeps the stored one, except when it replaces a - // reference: the reference is then dropped for the empty value. + // An empty value keeps the stored one only while the baseline is empty too + // (a secret never loaded): clearing a value or reference that was shown saves it empty. value: - s.variable.value == '' && - !(isExternalRef(ini.variable.value) && !isExternalRef(s.variable.value)) - ? undefined - : s.variable.value, + s.variable.value == '' && ini.variable.value == '' ? undefined : s.variable.value, is_secret: ini.variable.is_secret != s.variable.is_secret ? s.variable.is_secret : undefined, description: diff --git a/frontend/src/lib/components/WorkerGroup.svelte b/frontend/src/lib/components/WorkerGroup.svelte index ef33baace3..6711aada47 100644 --- a/frontend/src/lib/components/WorkerGroup.svelte +++ b/frontend/src/lib/components/WorkerGroup.svelte @@ -114,6 +114,7 @@ object_store_cache_config?: ObjectStoreConfig paused?: boolean serves_dev_workspaces?: boolean + fairness_reserve?: boolean } = $state({}) function loadNConfig() { @@ -224,12 +225,15 @@ object_store_cache_config?: ObjectStoreConfig paused?: boolean serves_dev_workspaces?: boolean + fairness_reserve?: boolean } activeWorkers: number customTags: string[] | undefined workers: [string, WorkerPing[]][] isAgent?: boolean defaultTagPerWorkspace?: boolean | undefined + /** undefined while unknown: the reserve toggle then stays shown */ + workspaceFairnessEnabled?: boolean | undefined width: number shouldAutoOpenDrawer?: boolean onDrawerOpened?: () => void @@ -246,6 +250,7 @@ workers, isAgent = false, defaultTagPerWorkspace = undefined, + workspaceFairnessEnabled = undefined, width = 0, shouldAutoOpenDrawer = false, onDrawerOpened = () => {}, @@ -340,14 +345,14 @@ orderedJsonStringify(replaceFalseWithUndefined(cleanWorkerGroupConfig({ v: c[k] }))) const changed = (k: keyof typeof nconfig) => comparable(saved, k) !== comparable(body, k) const restartFieldChanged = RESTART_FIELDS.some(changed) - const onlyPauseChanged = - changed('paused') && + const onlyLiveFieldsChanged = + (changed('paused') || changed('fairness_reserve')) && !restartFieldChanged && !OTHER_WORKER_FIELDS.some(changed) && !hasEnvVarChanges const dedicated = body.dedicated_worker != undefined || (body.dedicated_workers?.length ?? 0) > 0 - return !onlyPauseChanged && (dedicated || restartFieldChanged) + return !onlyLiveFieldsChanged && (dedicated || restartFieldChanged) } async function saveConfig(body: typeof nconfig) { @@ -941,6 +946,43 @@ disabled={!canEditConfig} /> </Label> + {#if !isAgent && (workspaceFairnessEnabled !== false || config?.fairness_reserve === true)} + <div class="mt-8"></div> + <Label label="Fairness reserve" eeOnly={!hasEnterpriseFeatures}> + {#snippet header()} + <Tooltip> + {#snippet text()} + Keeps this group's capacity for the workspaces that workspace fairness does not cap. + While no workspace is capped, the group pulls no jobs at all. While one is, it only + pulls jobs of the other workspaces, including suspended jobs that are resumed. + Workers pick the change up within about 10 seconds, without restarting. + {/snippet} + </Tooltip> + {/snippet} + <Toggle + size="sm" + options={{ right: 'Reserve this group for workspaces not capped by fairness' }} + checked={nconfig?.fairness_reserve === true} + on:change={(ev) => { + if (nconfig !== undefined) { + nconfig.fairness_reserve = ev.detail ? true : undefined + } + }} + disabled={!canEditEEConfig} + /> + {#if workspaceFairnessEnabled === false && nconfig?.fairness_reserve === true} + <Alert size="xs" type="warning" title="Workspace fairness is off"> + This group pulls no jobs while workspace fairness is off in the instance settings. + Turn the reserve off, or enable workspace fairness. + </Alert> + {:else} + <p class="text-2xs text-secondary"> + Idle until a workspace is capped. Requires workspace fairness to be enabled in the + instance settings, otherwise the group never pulls a job. + </p> + {/if} + </Label> + {/if} <div class="mt-8"></div> <Label label="Worker proxy"> {#snippet header()} @@ -1528,6 +1570,21 @@ </Tooltip> </Badge> {/if} + {#if config?.fairness_reserve === true && !isAgent} + <Badge color={workspaceFairnessEnabled === false ? 'yellow' : 'indigo'} small> + Fairness reserve + <Tooltip> + {#snippet text()} + {#if workspaceFairnessEnabled === false} + Workspace fairness is off in the instance settings, so this group pulls no jobs. + {:else} + Pulls jobs only while workspace fairness caps a workspace, and then only jobs of + the workspaces it does not cap. Idle otherwise. + {/if} + {/snippet} + </Tooltip> + </Badge> + {/if} </div> {#if vcpus_memory?.vcpus} diff --git a/frontend/src/lib/components/WorkflowTimeline.svelte b/frontend/src/lib/components/WorkflowTimeline.svelte index 4526281293..08689102ba 100644 --- a/frontend/src/lib/components/WorkflowTimeline.svelte +++ b/frontend/src/lib/components/WorkflowTimeline.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { displayDate, msToSec, emptyString } from '$lib/utils' + import { displayDate, msToCompactDuration, emptyString } from '$lib/utils' import { onDestroy } from 'svelte' import { getDbClockNow } from '$lib/forLater' import { ChevronDown, ChevronRight, Loader2, Moon, ShieldCheck } from 'lucide-svelte' @@ -179,13 +179,13 @@ <div class="col-span-11 pt-1 px-2 flex text-2xs text-secondary justify-between"> <div>{min ? displayDate(new Date(min), true) : ''}</div> {#if max && min} - <div class="hidden lg:block">{msToSec(max - min)}s</div> + <div class="hidden lg:block">{msToCompactDuration(max - min, 1)}</div> {/if} <div class="flex gap-1 items-center font-mono"> {max ? displayDate(new Date(max), true) : ''} {#if !max && min} {#if now} - {msToSec(now - min, 3)}s + {msToCompactDuration(now - min, 1)} {/if} <Loader2 size={14} class="animate-spin" /> {/if} @@ -264,7 +264,7 @@ </div> {/if} {:else} - <span class="text-tertiary">{msToSec(v.duration_ms ?? 0)}s</span> + <span class="text-tertiary">{msToCompactDuration(v.duration_ms ?? 0)}</span> {/if} </div> {#if canApprove && selfApprovalDisabled && actingUser?.is_admin} @@ -354,6 +354,7 @@ {total} {min} gray + followedByBar={!!startedAt} started_at={scheduledFor} len={waitingLen < 100 ? 0 : waitingLen - 100} running={!flowDone && startedAt == undefined} diff --git a/frontend/src/lib/components/WorkspaceItemKindIcon.svelte b/frontend/src/lib/components/WorkspaceItemKindIcon.svelte index 9d07f6ef89..53ba386ef6 100644 --- a/frontend/src/lib/components/WorkspaceItemKindIcon.svelte +++ b/frontend/src/lib/components/WorkspaceItemKindIcon.svelte @@ -3,7 +3,7 @@ The glyph the rest of the app gives a workspace item's kind (see RowIcon), at the caller's size. --> <script lang="ts"> - import { Code2, LayoutDashboard } from 'lucide-svelte' + import { Bot, Code2, LayoutDashboard } from 'lucide-svelte' import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte' import type { WorkspaceItemKind } from '$lib/components/workspacePicker' @@ -14,6 +14,8 @@ The glyph the rest of the app gives a workspace item's kind (see RowIcon), at th <BarsStaggered {size} class="flex-shrink-0 text-teal-500" /> {:else if kind === 'app'} <LayoutDashboard {size} class="flex-shrink-0 text-orange-500" /> +{:else if kind === 'agent'} + <Bot {size} class="flex-shrink-0 text-violet-500" /> {:else} <Code2 {size} class="flex-shrink-0 text-blue-500" /> {/if} diff --git a/frontend/src/lib/components/access/GrantNavigator.svelte b/frontend/src/lib/components/access/GrantNavigator.svelte index bae5601a11..96c33d52ea 100644 --- a/frontend/src/lib/components/access/GrantNavigator.svelte +++ b/frontend/src/lib/components/access/GrantNavigator.svelte @@ -1,18 +1,21 @@ <!-- @component The access view's "+ Grant" list: the caller's own `u/` folder and every folder, with their items. -Picking a row grants the principal read on it; the "All of f/x" row grants the whole folder. +A row does nothing when clicked. The highlighted row offers each change to the principal's own +grant on it that changes what the principal can do (grant read or write, revoke write or read), +the most useful one as its button and the others in its dropdown. The "All of f/x" row +changes the grant on the whole folder. --> <script module lang="ts"> - /** The navigator's tallest height, `max-h-[min(420px,60vh)]` below, for its host to place it. */ + /** The navigator's tallest height, `max-h-[min(460px,60vh)]` below, for its host to place it. */ export function navigatorMaxHeight(): number { - return Math.min(420, window.innerHeight * 0.6) + return Math.min(460, window.innerHeight * 0.6) } </script> <script lang="ts"> import DrillPicker from '$lib/components/DrillPicker.svelte' - import type { DrillLeaf, DrillNode } from '$lib/components/drillPicker' + import type { DrillLeaf, DrillLeafAction, DrillNode } from '$lib/components/drillPicker' import RowIcon from '$lib/components/common/table/RowIcon.svelte' import { GranularAclService, @@ -27,9 +30,10 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w } from '$lib/components/operatingWorkspace.svelte' import { sendUserToast } from '$lib/toast' import { debounce } from '$lib/utils' - import { Folder, ScanSearch, User, Users } from 'lucide-svelte' - import { setGrant } from './access' - import type { RunnableKind } from './detectNeeds' + import { Folder, User, Users } from 'lucide-svelte' + import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' + import { setOverlayHost } from '$lib/components/common/overlayHost.svelte' + import { setGrant, type GrantLevel, type GrantSource } from './access' const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() @@ -37,26 +41,54 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w type Row = BrowseAccessItemsResponse['items'][number] /** `kind` `folder` is the "All of f/x" row, its `path` the folder name. */ type Leaf = Row & { owner?: boolean } + /** What the principal holds on a row besides its own entry: the level, `undefined` where the + * access report cannot tell, and where it comes from, in the access table's words. */ + type Inherited = { level: GrantLevel | undefined; hows: string[] } let { principal, access, - onGranted, - onFindReads + onChange, + source }: { principal: string access: PrincipalAccess - onGranted: () => void - onFindReads: (kind: RunnableKind, path: string) => void + /** After each change to a grant, for the host to reload `access`. */ + onChange: () => void + source?: GrantSource } = $props() - const own = $derived(`u/${operatingUser.current?.username}`) + const api: GrantSource = { + get ownSpace() { + return `u/${operatingUser.current?.username}` + }, + folders: () => + GranularAclService.browseAccessFolders({ workspace: $operatingWorkspace!, principal }), + items: (query) => + GranularAclService.browseAccessItems({ + workspace: $operatingWorkspace!, + principal, + ...query + }), + set: (kind, path, level) => setGrant($operatingWorkspace!, kind, path, principal, level) + } + const data = $derived(source ?? api) + const own = $derived(data.ownSpace) + let picker: { focus: () => void; escape: (target: EventTarget | null) => boolean } | undefined = + $state() let folders: BrowseAccessFoldersResponse | undefined = $state() /** Rows by top-level branch (`u/alice`, `f/billing`), then by `kind:path`. */ let rows: Record<string, Record<string, Row>> = $state({}) let loading: Record<string, boolean> = $state({}) const loaded = new Set<string>() + /** Branches whose every page has arrived, so no rows there means the folder has no items. */ + let complete: Record<string, boolean> = $state({}) + /** The change in flight, as `kind:path:label`. */ + let pending: string | undefined = $state() + /** Runs before this time are ignored: the second press of a double click or Enter would + * otherwise run the button that took the first one's place. */ + let settledUntil = 0 function branchOf(path: string): string { return path.split('/', 2).join('/') @@ -72,10 +104,7 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w async function loadFolders() { try { - folders = await GranularAclService.browseAccessFolders({ - workspace: $operatingWorkspace!, - principal - }) + folders = await data.folders() } catch (e) { sendUserToast(`Could not load folders: ${e?.body ?? e}`, true) } @@ -88,18 +117,14 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w try { let offset = 0 while (true) { - const page = await GranularAclService.browseAccessItems({ - workspace: $operatingWorkspace!, - principal, - prefix: `${branch}/`, - offset - }) + const page = await data.items({ prefix: `${branch}/`, offset }) merge(page.items) // The branch shows from its first page; later pages fill it in as they arrive. loading[branch] = false if (!page.has_more) break offset += page.items.length } + complete[branch] = true } catch (e) { loaded.delete(branch) sendUserToast(`Could not load ${branch}: ${e?.body ?? e}`, true) @@ -111,12 +136,7 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w // The picker searches only the rows it holds, so matches anywhere are fetched into the tree. const searchSoon = debounce(async (search: string) => { try { - const page = await GranularAclService.browseAccessItems({ - workspace: $operatingWorkspace!, - principal, - search - }) - merge(page.items) + merge((await data.items({ search })).items) } catch (e) { sendUserToast(`Could not search: ${e?.body ?? e}`, true) } @@ -142,6 +162,16 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w .map(itemLeaf) } + function folderData(folder: BrowseAccessFoldersResponse[number]): Leaf { + return { + kind: 'folder', + path: folder.name, + grant: folder.grant, + blocked: folder.blocked, + owner: folder.target_owner + } + } + const tree = $derived.by<DrillNode<Leaf>[]>(() => { const folderNames = new Set((folders ?? []).map((f) => `f/${f.name}`)) const others = Object.keys(rows) @@ -157,33 +187,35 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w loading: loading[own], children: itemLeaves(own) }, - ...(folders ?? []).map( - (folder): DrillNode<Leaf> => ({ + ...(folders ?? []).map((folder): DrillNode<Leaf> => { + const branch = `f/${folder.name}` + const items = itemLeaves(branch) + const level = levelOf(folderData(folder), `folder:${folder.name}`) + return { type: 'branch', - key: `f/${folder.name}`, - label: `f/${folder.name}`, + key: branch, + label: branch, icon: Folder, searchGroup: true, - loading: loading[`f/${folder.name}`], + loading: loading[branch], + badge: level === 'none' ? undefined : LEVEL_LABELS[level], + note: + complete[branch] && items.length === 0 + ? `${branch} has no items yet. A grant on the whole folder covers the items added later.` + : undefined, children: [ { type: 'leaf', key: `folder:${folder.name}`, label: `All of f/${folder.name}`, - searchableText: `f/${folder.name}`, - data: { - kind: 'folder', - path: folder.name, - grant: folder.grant, - blocked: folder.blocked, - owner: folder.target_owner - }, + searchableText: branch, + data: folderData(folder), disabled: folder.target_owner || !!folder.blocked }, - ...itemLeaves(`f/${folder.name}`) + ...items ] - }) - ), + } + }), // Other users' and groups' items appear once a search finds them. ...others.map( (b): DrillNode<Leaf> => ({ @@ -198,55 +230,253 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w ] }) - const reaches = $derived( - new Map<string, boolean>([ - ...access.items.map((i) => [`${i.kind}:${i.path}`, i.write] as const), - ...access.folders.map((f) => [`folder:${f.name}`, f.write] as const) - ]) - ) - /** How the principal reaches each item it reaches, by `kind:path`. */ const reasons = $derived( new Map<string, AccessReason[]>( access.items.map((i) => [`${i.kind}:${i.path}`, i.reasons] as const) ) ) + const reachedFolders = $derived(new Map(access.folders.map((f) => [f.name, f]))) - async function grant(leaf: DrillLeaf<Leaf>) { - const row = leaf.data - if (row.grant != undefined) return - try { - await setGrant($operatingWorkspace!, row.kind, row.path, principal, 'read') - row.grant = false - if (row.kind === 'folder') { - const folder = folders?.find((f) => f.name === row.path) - if (folder) folder.grant = false - } - onGranted() - } catch (e) { - const what = row.kind === 'folder' ? `f/${row.path}` : row.path - sendUserToast(`Could not grant ${what}: ${e?.body ?? e}`, true) + const isGroup = $derived(principal.startsWith('g/')) + const who = $derived(isGroup ? `members of ${principal}` : principal) + + /** What read and write let the principal do, by kind. */ + const GIVES: Record<string, { read: string; write: string }> = { + folder: { read: 'read all its items, new ones included', write: 'edit and add items' }, + script: { read: 'see and run it', write: 'edit it' }, + flow: { read: 'see and run it', write: 'edit it' }, + app: { read: 'open and use it', write: 'edit it' }, + raw_app: { read: 'open and use it', write: 'edit it' }, + resource: { read: 'use it and see its value', write: 'change its value' }, + variable: { read: 'use it and see its value', write: 'change its value' }, + schedule: { read: 'see it', write: 'edit, enable and disable it' } + } + const GIVES_OTHER = { read: 'see it', write: 'edit it' } + + const LEVELS: GrantLevel[] = ['none', 'read', 'write'] + const LEVEL_LABELS: Record<GrantLevel, string> = { + none: 'No access', + read: 'Read', + write: 'Write' + } + + function maxLevel(a: GrantLevel, b: GrantLevel): GrantLevel { + return LEVELS.indexOf(a) >= LEVELS.indexOf(b) ? a : b + } + + function entryLevel(grant: boolean | null | undefined): GrantLevel { + return grant == undefined ? 'none' : grant ? 'write' : 'read' + } + + /** The principal's own entry on an item, which `grant` on its row holds. */ + function isOwnEntry(r: AccessReason): boolean { + return r.type === 'user' || (r.type === 'group' && `g/${r.group}` === principal) + } + + function reasonLabel(r: AccessReason): string { + switch (r.type) { + case 'folder': + return `through f/${r.folder}` + case 'group': + return `through g/${r.group}` + case 'own': + return `under ${principal}/` + case 'group_path': + return `under g/${r.group}/` + default: + return 'shared directly' } } - function tooltip(leaf: DrillLeaf<Leaf>): string | undefined { - const row = leaf.data - if (row.owner) return `${principal} owns f/${row.path} and always keeps write` - if (row.blocked) return row.blocked - if (row.grant != undefined) - return `Already granted ${row.grant ? 'write' : 'read'}: change it from the table` - const write = reaches.get(leaf.key) - if (write === undefined) return undefined - const already = `Already ${write ? 'writes' : 'reads'} it` - const folder = reasons.get(leaf.key)?.find((r) => r.type === 'folder')?.folder - return folder - ? `${already} through f/${folder}: picking it adds a direct grant, which stays even if f/${folder} is no longer shared` - : `${already}: picking it adds a direct grant, which stays even if that access is removed` + function inheritedOf(row: Leaf, key: string): Inherited { + if (row.kind === 'folder') { + if (row.owner) return { level: 'write', hows: ['folder admin'] } + const folder = reachedFolders.get(row.path) + const others = (folder?.via ?? []).filter((v) => v !== principal) + if (!folder || others.length === 0) return { level: 'none', hows: [] } + // `via` names the other entries without their levels, so next to the principal's own + // write the report cannot tell whether one of them gives write too. + const level = folder.grant === true ? undefined : folder.write ? 'write' : 'read' + return { level, hows: others.map((v) => `through ${v}`) } + } + const others = (reasons.get(key) ?? []).filter((r) => !isOwnEntry(r)) + const level: GrantLevel = + others.length === 0 + ? 'none' + : others.some((r) => r.type === 'own' || r.type === 'group_path' || r.write) + ? 'write' + : 'read' + return { level, hows: others.map(reasonLabel) } } - /** The kind detectNeeds reads it as: a full-code app is read like any app. */ - function runnableKind(kind: string): RunnableKind | undefined { - if (kind === 'raw_app') return 'app' - return kind === 'flow' || kind === 'script' || kind === 'app' ? kind : undefined + /** The level held on a row. The own entry is read from the row, which a change made here + * updates before `access` reloads. */ + function levelOf(row: Leaf, key: string): GrantLevel { + return maxLevel(inheritedOf(row, key).level ?? 'read', entryLevel(row.grant)) + } + + function pathOf(row: Leaf): string { + return row.kind === 'folder' ? `f/${row.path}` : row.path + } + + /** Why a dimmed row can't be changed, for its tooltip. */ + function lockedText(row: Leaf): string | undefined { + if (row.owner) + return `${principal} is an admin of f/${row.path}, so ${isGroup ? 'its members' : 'they'} can write every item in it.` + return row.blocked + } + + /** Selected on a highlighted row, the first of these it offers. */ + const PREFERRED = ['Grant read', 'Grant write', 'Revoke write', 'Revoke read'] + + function actionsFor(leaf: DrillLeaf<Leaf>): DrillLeafAction[] { + const row = leaf.data + const ownLevel = entryLevel(row.grant) + const inherited = inheritedOf(row, leaf.key) + const level = maxLevel(inherited.level ?? 'read', ownLevel) + const gives = GIVES[row.kind] ?? GIVES_OTHER + // In the order of the level each one leaves, so the buttons read from less to more access. + const changes: { label: string; to: GrantLevel; hint: string }[] = [] + if (ownLevel !== 'none' && inherited.level === 'none') { + changes.push({ + label: 'Revoke read', + to: 'none', + hint: `${who} can no longer ${gives.read}.` + }) + } + if (level === 'none') { + changes.push({ label: 'Grant read', to: 'read', hint: `${who} can ${gives.read}.` }) + } + if (ownLevel === 'write' && inherited.level !== 'write') { + changes.push({ + label: 'Revoke write', + to: 'read', + hint: inherited.level + ? `${who} can no longer ${gives.write}, only ${gives.read}.` + : `the grant becomes read, but ${who} may still write ${inherited.hows.join(' or ')}.` + }) + } + if (level !== 'write') { + const folder = + row.kind !== 'folder' && ownLevel === 'none' + ? (reasons.get(leaf.key) ?? []).find((r) => r.type === 'folder')?.folder + : undefined + changes.push({ + label: 'Grant write', + to: 'write', + hint: + level === 'none' + ? `${who} can ${gives.read}, and ${gives.write}.` + : `${who} can also ${gives.write}.` + + (folder ? ` This grant stays if f/${folder} is no longer shared.` : '') + }) + } + const preferred = PREFERRED.find((label) => changes.some((c) => c.label === label)) + return changes.map((c) => ({ + label: c.label, + hint: c.hint, + preferred: c.label === preferred, + loading: pending === `${leaf.key}:${c.label}`, + disabled: pending !== undefined, + run: () => change(leaf, c.label, c.to) + })) + } + + /** A change to a whole folder, waiting for the dialog. */ + let confirming: + | { leaf: DrillLeaf<Leaf>; label: string; level: GrantLevel; hint: string } + | undefined = $state() + + function change(leaf: DrillLeaf<Leaf>, label: string, level: GrantLevel) { + if (pending !== undefined || Date.now() < settledUntil) return + if (leaf.data.kind !== 'folder') { + apply(leaf, label, level) + return + } + const hint = actionsFor(leaf).find((a) => a.label === label)?.hint ?? '' + confirming = { leaf, label, level, hint } + // Else the second press of a double click or Enter would confirm it at once. + settledUntil = Date.now() + 400 + } + + async function confirmFolder() { + if (!confirming || pending !== undefined || Date.now() < settledUntil) return + await apply(confirming.leaf, confirming.label, confirming.level) + confirming = undefined + } + + function cancelFolder() { + if (pending !== undefined) return + confirming = undefined + picker?.focus() + } + + /** Focus stays in the search field under the dialog, so its keys are answered here: the + * dialog's own window listener leaves alone keys that start inside a popover, which is where + * the access drawer shows this list. */ + function dialogKeys(e: KeyboardEvent) { + if (!confirming || e.key === 'Tab') return + e.stopPropagation() + // A focused dialog button activates itself, so Enter on Cancel cancels. + const onButton = !!(e.target as HTMLElement | null)?.closest?.('[role="dialog"] button') + if (onButton && (e.key === 'Enter' || e.key === ' ')) return + e.preventDefault() + if (e.key === 'Enter') confirmFolder() + else if (e.key === 'Escape') cancelFolder() + } + + /** Answers an Escape a host takes before the navigator can: cancels the folder dialog, or + * passes it to the picker. False when nothing here was open, so the host closes instead. */ + export function escape(target: EventTarget | null): boolean { + if (confirming) { + cancelFolder() + return true + } + return !!picker?.escape(target) + } + + let root: HTMLElement | undefined = $state() + // The dialog covers this list rather than the page: a click on a dialog over the page lands + // outside the drawer's popover, which closes it and the dialog with it. + setOverlayHost({ el: () => root, drawers: { val: [] }, active: () => true }) + + const DONE: Record<string, string> = { + 'Grant read': 'Read granted', + 'Grant write': 'Write granted', + 'Revoke write': 'Write revoked', + 'Revoke read': 'Access revoked' + } + + /** The row a change just landed on, and what it did ("Read granted"), for 1.5s. */ + let done: { key: string; text: string } | undefined = $state() + let doneTimer: ReturnType<typeof setTimeout> | undefined + + function showDone(key: string, text: string) { + clearTimeout(doneTimer) + done = { key, text } + doneTimer = setTimeout(() => (done = undefined), 1000) + } + + async function apply(leaf: DrillLeaf<Leaf>, label: string, level: GrantLevel) { + const row = leaf.data + pending = `${leaf.key}:${label}` + try { + await data.set(row.kind, row.path, level) + row.grant = level === 'none' ? null : level === 'write' + if (row.kind === 'folder') { + const folder = folders?.find((f) => f.name === row.path) + if (folder) folder.grant = row.grant + } + onChange() + showDone(leaf.key, DONE[label] ?? 'Done') + } catch (e) { + sendUserToast(`Could not ${label.toLowerCase()} on ${pathOf(row)}: ${e?.body ?? e}`, true) + } finally { + pending = undefined + settledUntil = Date.now() + 400 + // A click left focus on a button, which may be gone now. + picker?.focus() + } } </script> @@ -254,31 +484,41 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w <RowIcon kind={leaf.data.kind as 'folder'} size={12} /> {/snippet} -<div class="flex flex-col max-h-[min(420px,60vh)]"> +<div + bind:this={root} + class="relative flex flex-col max-h-[min(460px,60vh)]" + onkeydowncapture={dialogKeys} + role="presentation" +> + {#if confirming} + {@const folder = pathOf(confirming.leaf.data)} + <ConfirmationModal + open + title="{confirming.label} on {folder}?" + confirmationText={confirming.label} + type={confirming.label.startsWith('Revoke') ? 'danger' : 'info'} + loading={pending !== undefined} + onConfirmed={confirmFolder} + onCanceled={cancelFolder} + > + <p>It applies to every item in {folder}: {confirming.hint}</p> + </ConfirmationModal> + {/if} <DrillPicker + bind:this={picker} {tree} - onPick={grant} {leafIcon} + rowTooltip={(leaf) => lockedText(leaf.data)} rootLoading={!folders} onScopeChange={(scope) => scope.length === 1 && loadBranch(scope[0])} onFilterChange={(filter) => filter.trim() && searchSoon(filter.trim())} - rowTooltip={tooltip} + leafActions={actionsFor} + leafDone={(leaf) => (done && done.key === leaf.key ? done.text : undefined)} leafBadge={(leaf) => { - const write = reaches.get(leaf.key) - return write === undefined + const level = levelOf(leaf.data, leaf.key) + return level === 'none' ? undefined - : { label: write ? 'Writes' : 'Reads', color: write ? 'blue' : 'gray' } - }} - leafAction={(leaf) => { - const kind = runnableKind(leaf.data.kind) - return kind - ? { - icon: ScanSearch, - label: 'What it reads', - title: `Grant what ${leaf.data.path} reads when it runs`, - run: () => onFindReads(kind, leaf.data.path) - } - : undefined + : { label: LEVEL_LABELS[level], color: level === 'write' ? 'blue' : 'gray' } }} /> </div> diff --git a/frontend/src/lib/components/access/access.ts b/frontend/src/lib/components/access/access.ts index 1d62d52d33..08d8df97bb 100644 --- a/frontend/src/lib/components/access/access.ts +++ b/frontend/src/lib/components/access/access.ts @@ -1,7 +1,26 @@ -import { GranularAclService } from '$lib/gen' +import { + GranularAclService, + type BrowseAccessFoldersResponse, + type BrowseAccessItemsResponse +} from '$lib/gen' export type GrantLevel = 'none' | 'read' | 'write' +/** Where the Grant navigator reads and changes grants. Without one it uses the API, in the + * operating workspace. */ +export type GrantSource = { + /** The caller's own `u/` space, listed first. */ + ownSpace: string + folders: () => Promise<BrowseAccessFoldersResponse> + items: (query: { + prefix?: string + search?: string + offset?: number + }) => Promise<BrowseAccessItemsResponse> + /** Sets the principal's own entry, as `setGrant` does. */ + set: (kind: string, path: string, level: GrantLevel) => Promise<void> +} + type AclKind = Parameters<typeof GranularAclService.addGranularAcls>[0]['kind'] export const KIND_LABELS: Record<string, string> = { diff --git a/frontend/src/lib/components/agentTrace.ts b/frontend/src/lib/components/agentTrace.ts index 013d4a65ac..766a3c7c2d 100644 --- a/frontend/src/lib/components/agentTrace.ts +++ b/frontend/src/lib/components/agentTrace.ts @@ -16,7 +16,11 @@ export type AgentTraceEntry = kind: 'tool' name: string args?: string - result: string + /** Absent while a streamed call is still running. */ + result?: string + running?: boolean + /** What a stream reports; a finished trace reads the outcome off the tool's job. */ + failed?: boolean /** Present for a flow-module tool, which runs as its own job. */ jobId?: string /** An MCP tool runs in the worker, so it names its server instead. */ diff --git a/frontend/src/lib/components/aiAgentResult.test.ts b/frontend/src/lib/components/aiAgentResult.test.ts index 6757104055..6389295a70 100644 --- a/frontend/src/lib/components/aiAgentResult.test.ts +++ b/frontend/src/lib/components/aiAgentResult.test.ts @@ -109,11 +109,13 @@ describe('agent stream', () => { expect(completed.stream.current).toBe('eu-central-1 is down!') }) - it('marks a tool still running, and a failed one', () => { - const started = '{"type":"tool_execution","call_id":"c1","function_name":"fetch"}\n' + it('marks a tool still running, and a failed one with what it was given and returned', () => { + const started = + '{"type":"tool_call_arguments","call_id":"c1","function_name":"fetch","arguments":"{\\"url\\":\\"x\\"}"}\n' + + '{"type":"tool_execution","call_id":"c1","function_name":"fetch"}\n' const running = advanceAgentStream(started, emptyAgentStreamProgress()) expect(running.stream.entries).toEqual([ - { kind: 'tool', callId: 'c1', name: 'fetch', running: true, success: undefined } + { kind: 'tool', callId: 'c1', name: 'fetch', running: true, args: '{"url":"x"}' } ]) const failed = advanceAgentStream( started + @@ -122,7 +124,15 @@ describe('agent stream', () => { ) // One row for the call, not one per event about it. expect(failed.stream.entries).toEqual([ - { kind: 'tool', callId: 'c1', name: 'fetch', running: false, success: false } + { + kind: 'tool', + callId: 'c1', + name: 'fetch', + running: false, + success: false, + args: '{"url":"x"}', + result: 'boom' + } ]) }) }) diff --git a/frontend/src/lib/components/aiAgentResult.ts b/frontend/src/lib/components/aiAgentResult.ts index 563d9b7292..0c4bf0377d 100644 --- a/frontend/src/lib/components/aiAgentResult.ts +++ b/frontend/src/lib/components/aiAgentResult.ts @@ -184,7 +184,15 @@ export function summarizeAgentResult(result: AgentResult): AgentResultSummary { export type AgentStreamEntry = | { kind: 'assistant'; content: string } - | { kind: 'tool'; callId: string; name: string; running: boolean; success?: boolean } + | { + kind: 'tool' + callId: string + name: string + running: boolean + success?: boolean + args?: string + result?: string + } export type AgentStream = { /** @@ -230,6 +238,10 @@ function isWellFormedEvent(event: AgentStreamEvent): boolean { if (event.type === 'token_delta' || event.type === 'reasoning_token_delta') { return typeof event.content === 'string' } + // Says the agent waits on its background tools, which the run page shows on their rows. + if (event.type === 'background_wait') { + return false + } return ( typeof event.call_id === 'string' && event.call_id !== '' && @@ -278,7 +290,7 @@ export function advanceAgentStream( } const stream: AgentStream = { ...previous.stream, entries: [...previous.stream.entries] } for (const event of parseStreamEvents(raw.slice(previous.consumed, complete))) { - if (!isWellFormedEvent(event)) { + if (!isWellFormedEvent(event) || event.type === 'background_wait') { continue } if (event.type === 'token_delta') { @@ -311,17 +323,19 @@ export function advanceAgentStream( e.kind === 'tool' && e.callId === event.call_id ) const settled = event.type === 'tool_result' - if (existing) { - existing.running = !settled - existing.success = settled ? event.success === true : existing.success - } else { - stream.entries.push({ - kind: 'tool', - callId: event.call_id, - name: event.function_name, - running: !settled, - success: settled ? event.success === true : undefined - }) + let entry = existing + if (!entry) { + entry = { kind: 'tool', callId: event.call_id, name: event.function_name, running: true } + stream.entries.push(entry) + } + entry.running = !settled + if (settled) { + entry.success = event.success === true + if (typeof event.result === 'string') entry.result = event.result + } + // Sent whole once the model has finished writing them, not as deltas. + if (event.type === 'tool_call_arguments' && typeof event.arguments === 'string') { + entry.args = event.arguments || undefined } } return { consumed: complete, stream } diff --git a/frontend/src/lib/components/apps/components/display/AppMap.svelte b/frontend/src/lib/components/apps/components/display/AppMap.svelte index 1f04716110..2cf41dda0d 100644 --- a/frontend/src/lib/components/apps/components/display/AppMap.svelte +++ b/frontend/src/lib/components/apps/components/display/AppMap.svelte @@ -224,12 +224,13 @@ } }) $effect(() => { - if (map && resolvedConfig.longitude && resolvedConfig.latitude) { + // 0 is a real coordinate and zoom level, so check for a value rather than truthiness. + if (map && resolvedConfig.longitude != undefined && resolvedConfig.latitude != undefined) { map.getView().setCenter([resolvedConfig.longitude, resolvedConfig.latitude]) } }) $effect(() => { - if (map && resolvedConfig.zoom) { + if (map && resolvedConfig.zoom != undefined) { map.getView().setZoom(resolvedConfig.zoom) } }) diff --git a/frontend/src/lib/components/apps/components/display/InsertRowDrawerButton.svelte b/frontend/src/lib/components/apps/components/display/InsertRowDrawerButton.svelte index 386b07c520..e78899e80f 100644 --- a/frontend/src/lib/components/apps/components/display/InsertRowDrawerButton.svelte +++ b/frontend/src/lib/components/apps/components/display/InsertRowDrawerButton.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import { Alert, Drawer, DrawerContent, Button, ButtonType } from '$lib/components/common' import { CornerDownLeft, Plus } from 'lucide-svelte' import InsertRow from './dbtable/InsertRow.svelte' @@ -49,7 +50,7 @@ } </script> -<svelte:window +<HostWindow onkeydown={(e) => { if (drawerOpen && (e.ctrlKey || e.metaKey) && e.key === 'Enter') { onConfirm() diff --git a/frontend/src/lib/components/apps/components/display/dbtable/queries/count.ts b/frontend/src/lib/components/apps/components/display/dbtable/queries/count.ts index b93a1d669d..ee25208d3e 100644 --- a/frontend/src/lib/components/apps/components/display/dbtable/queries/count.ts +++ b/frontend/src/lib/components/apps/components/display/dbtable/queries/count.ts @@ -63,11 +63,11 @@ export function makeCountQuery( break case 'ms_sql_server': if (filteredColumns.length > 0) { - quicksearchCondition += `(@p1 = '' OR CONCAT(${filteredColumns.join( + quicksearchCondition += `(@P1 = '' OR CONCAT(${filteredColumns.join( ', +' - )}) LIKE '%' + @p1 + '%')` + )}) LIKE '%' + @P1 + '%')` } else { - quicksearchCondition += `(@p1 = '' OR 1 = 1)` + quicksearchCondition += `(@P1 = '' OR 1 = 1)` } query += `SELECT COUNT(*) as count FROM [${table}]` break diff --git a/frontend/src/lib/components/apps/components/display/dbtable/queries/delete.ts b/frontend/src/lib/components/apps/components/display/dbtable/queries/delete.ts index 3c6419634b..cbef4275fe 100644 --- a/frontend/src/lib/components/apps/components/display/dbtable/queries/delete.ts +++ b/frontend/src/lib/components/apps/components/display/dbtable/queries/delete.ts @@ -41,7 +41,7 @@ export function makeDeleteQuery(table: string, columns: ColumnDef[], dbType: DbT } case 'ms_sql_server': { const conditions = columns - .map((c, i) => `(@p${i + 1} IS NULL AND ${c.field} IS NULL OR ${c.field} = @p${i + 1})`) + .map((c, i) => `(@P${i + 1} IS NULL AND ${c.field} IS NULL OR ${c.field} = @P${i + 1})`) .join('\n AND ') query += `\nDELETE FROM ${table} \nWHERE ${conditions}` return query diff --git a/frontend/src/lib/components/apps/components/display/dbtable/queries/insert.ts b/frontend/src/lib/components/apps/components/display/dbtable/queries/insert.ts index 7a79a3cbad..70afdc57a2 100644 --- a/frontend/src/lib/components/apps/components/display/dbtable/queries/insert.ts +++ b/frontend/src/lib/components/apps/components/display/dbtable/queries/insert.ts @@ -20,7 +20,7 @@ function formatInsertValues(columns: ColumnDef[], dbType: DbType, startIndex: nu case 'postgresql': return columns.map((c, i) => `$${startIndex + i}::${c.datatype}`).join(', ') case 'ms_sql_server': - return columns.map((c, i) => `@p${startIndex + i}`).join(', ') + return columns.map((c, i) => `@P${startIndex + i}`).join(', ') case 'snowflake': return columns.map(() => `?`).join(', ') case 'bigquery': diff --git a/frontend/src/lib/components/apps/components/display/dbtable/queries/select.ts b/frontend/src/lib/components/apps/components/display/dbtable/queries/select.ts index be01457434..14d57e785f 100644 --- a/frontend/src/lib/components/apps/components/display/dbtable/queries/select.ts +++ b/frontend/src/lib/components/apps/components/display/dbtable/queries/select.ts @@ -224,8 +224,8 @@ CASE WHEN :order_by = '${column.field}' AND :is_desc IS true THEN \`${column.fie .filter((column) => !unsortableTypes.includes(column.datatype.toLowerCase())) .map((column) => { return ` -(CASE WHEN @p4 = '${column.field}' AND @p5 = 0 THEN ${column.field} END) ASC, -(CASE WHEN @p4 = '${column.field}' AND @p5 = 1 THEN ${column.field} END) DESC` +(CASE WHEN @P4 = '${column.field}' AND @P5 = 0 THEN ${column.field} END) ASC, +(CASE WHEN @P4 = '${column.field}' AND @P5 = 1 THEN ${column.field} END) DESC` }) .join(',\n') @@ -239,13 +239,13 @@ CASE WHEN :order_by = '${column.field}' AND :is_desc IS true THEN \`${column.fie .join(', ') quicksearchCondition = searchClause - ? ` (@p3 = '' OR CONCAT(${searchClause}) LIKE '%' + @p3 + '%')` - : ` (@p3 = '')` + ? ` (@P3 = '' OR CONCAT(${searchClause}) LIKE '%' + @P3 + '%')` + : ` (@P3 = '')` query += `SELECT ${selectClause} FROM ${table}` query += ` WHERE ${whereClause ? `${whereClause} AND` : ''} ${quicksearchCondition}` query += ` ORDER BY ${orderBy}` - query += ` OFFSET @p2 ROWS FETCH NEXT @p1 ROWS ONLY` + query += ` OFFSET @P2 ROWS FETCH NEXT @P1 ROWS ONLY` break } case 'snowflake': { diff --git a/frontend/src/lib/components/apps/components/display/dbtable/queries/update.ts b/frontend/src/lib/components/apps/components/display/dbtable/queries/update.ts index b57fa4989b..176bc7eba6 100644 --- a/frontend/src/lib/components/apps/components/display/dbtable/queries/update.ts +++ b/frontend/src/lib/components/apps/components/display/dbtable/queries/update.ts @@ -51,9 +51,9 @@ export function makeUpdateQuery( } case 'ms_sql_server': { const conditions = columns - .map((c, i) => `(@p${i + 2} IS NULL AND ${c.field} IS NULL OR ${c.field} = @p${i + 2})`) + .map((c, i) => `(@P${i + 2} IS NULL AND ${c.field} IS NULL OR ${c.field} = @P${i + 2})`) .join('\n AND ') - query += `\nUPDATE ${table} SET ${column.field} = @p1 \nWHERE ${conditions}` + query += `\nUPDATE ${table} SET ${column.field} = @P1 \nWHERE ${conditions}` return query } case 'snowflake': { 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 ae3a82e97c..60d89ff9db 100644 --- a/frontend/src/lib/components/apps/components/display/dbtable/utils.ts +++ b/frontend/src/lib/components/apps/components/display/dbtable/utils.ts @@ -239,7 +239,8 @@ return schema }, mssql: { argName: 'database', - code: `select TABLE_SCHEMA, TABLE_NAME, DATA_TYPE, COLUMN_NAME, COLUMN_DEFAULT from information_schema.columns where table_schema != 'sys'`, + // Uppercase: under a case-sensitive collation `information_schema.columns` does not resolve. + code: `select TABLE_SCHEMA, TABLE_NAME, DATA_TYPE, COLUMN_NAME, COLUMN_DEFAULT from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA != 'sys'`, lang: 'mssql', processingFn: (rows) => { if (!rows || rows.length === 0) return {} @@ -442,7 +443,8 @@ export function buildParameters( case 'mysql': return `-- :${column.field} (${column.datatype.split('(')[0]})` case 'ms_sql_server': - return `-- @p${i + 1} ${column.field} (${column.datatype.split('(')[0]})` + // The executor binds `@P1..`; under a case-sensitive collation `@p1` is undeclared. + return `-- @P${i + 1} ${column.field} (${column.datatype.split('(')[0]})` case 'snowflake': return `-- ? ${column.field} (${column.datatype.split('(')[0]})` case 'bigquery': diff --git a/frontend/src/lib/components/apps/components/display/table/AppAggridTable.svelte b/frontend/src/lib/components/apps/components/display/table/AppAggridTable.svelte index 0fc216eedb..1048d09c45 100644 --- a/frontend/src/lib/components/apps/components/display/table/AppAggridTable.svelte +++ b/frontend/src/lib/components/apps/components/display/table/AppAggridTable.svelte @@ -344,7 +344,7 @@ const agColumnDefs = transformColumnDefs({ columnDefs: Array.isArray(resolvedConfig?.columnDefs) && resolvedConfig.columnDefs.every(isObject) - ? ([...resolvedConfig?.columnDefs] as WindmillColumnDef[]) + ? ([...resolvedConfig.columnDefs] as WindmillColumnDef[]) : [], actions, customActionsHeader: resolvedConfig?.customActionsHeader, @@ -492,7 +492,7 @@ const agColumnDefs = transformColumnDefs({ columnDefs: Array.isArray(resolvedConfig?.columnDefs) && resolvedConfig.columnDefs.every(isObject) - ? ([...resolvedConfig?.columnDefs] as WindmillColumnDef[]) + ? ([...resolvedConfig.columnDefs] as WindmillColumnDef[]) : [], actions, customActionsHeader: resolvedConfig?.customActionsHeader, diff --git a/frontend/src/lib/components/apps/components/inputs/AppRangeInput.svelte b/frontend/src/lib/components/apps/components/inputs/AppRangeInput.svelte index 0d87ae8ed4..6060bf3209 100644 --- a/frontend/src/lib/components/apps/components/inputs/AppRangeInput.svelte +++ b/frontend/src/lib/components/apps/components/inputs/AppRangeInput.svelte @@ -74,7 +74,9 @@ return `${v}` } $effect.pre(() => { - resolvedConfig.defaultLow != undefined || resolvedConfig.defaultHigh != undefined + // Both read on their own: joined with `||`, a set default low leaves default high untracked. + resolvedConfig.defaultLow + resolvedConfig.defaultHigh untrack(() => handleDefault()) }) $effect.pre(() => { diff --git a/frontend/src/lib/components/apps/components/inputs/AppSelectTab.svelte b/frontend/src/lib/components/apps/components/inputs/AppSelectTab.svelte index f11899b30e..edb2d0dcc6 100644 --- a/frontend/src/lib/components/apps/components/inputs/AppSelectTab.svelte +++ b/frontend/src/lib/components/apps/components/inputs/AppSelectTab.svelte @@ -85,7 +85,15 @@ let css = $state(initCss($app.css?.selecttabcomponent, untrack(() => customCss))) $effect.pre(() => { - selected === '' && resolvedConfig.defaultValue && untrack(() => setDefaultValue()) + // Not gated on an empty selection: once a tab is selected, the default would stop being tracked. + // An existing selection is only replaced by a default that is one of the tabs. + resolvedConfig.defaultValue && + untrack( + () => + (selected === '' || + resolvedConfig.items?.some((item) => item.value === resolvedConfig.defaultValue)) && + setDefaultValue() + ) }) $effect.pre(() => { selected && untrack(() => handleSelection(selected)) diff --git a/frontend/src/lib/components/apps/editor/AppTimeline.svelte b/frontend/src/lib/components/apps/editor/AppTimeline.svelte index b3b7540ed2..e414986623 100644 --- a/frontend/src/lib/components/apps/editor/AppTimeline.svelte +++ b/frontend/src/lib/components/apps/editor/AppTimeline.svelte @@ -149,6 +149,7 @@ {total} {min} gray + followedByBar={!!b.started_at} started_at={b.created_at} len={waitingLen < 100 ? 0 : waitingLen - 100} running={b?.started_at == undefined} diff --git a/frontend/src/lib/components/apps/editor/componentsPanel/QuickStyleMenu.svelte b/frontend/src/lib/components/apps/editor/componentsPanel/QuickStyleMenu.svelte index 676c59c12d..2aad033194 100644 --- a/frontend/src/lib/components/apps/editor/componentsPanel/QuickStyleMenu.svelte +++ b/frontend/src/lib/components/apps/editor/componentsPanel/QuickStyleMenu.svelte @@ -190,7 +190,8 @@ mounted && $styleStore && untrack(() => writeStyle()) }) $effect(() => { - mounted && (!value || value) && untrack(() => parseStyle()) + value + mounted && untrack(() => parseStyle()) }) $effect(() => { $app && untrack(() => setTopColors()) diff --git a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte index e3552d0e79..817d2a3e7f 100644 --- a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte +++ b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte @@ -367,16 +367,19 @@ Expand </Button> {#if hubFlowId} - <Button - variant="default" - size="xs" - startIcon={{ icon: GitFork }} - endIcon={{ icon: ExternalLink }} - target="_blank" - href="/flows/add?hub={hubFlowId}" - > - Fork - </Button> + <!-- A Hub flow's steps are usually inline code, which only `flows: full` may deploy. --> + {#if $roleCaps.flows === 'full'} + <Button + variant="default" + size="xs" + startIcon={{ icon: GitFork }} + endIcon={{ icon: ExternalLink }} + target="_blank" + href="/flows/add?hub={hubFlowId}" + > + Fork + </Button> + {/if} {:else} <Button variant="default" diff --git a/frontend/src/lib/components/apps/editor/settingsPanel/CSSMigrationModal.svelte b/frontend/src/lib/components/apps/editor/settingsPanel/CSSMigrationModal.svelte index f4250d44ae..eb15593dfa 100644 --- a/frontend/src/lib/components/apps/editor/settingsPanel/CSSMigrationModal.svelte +++ b/frontend/src/lib/components/apps/editor/settingsPanel/CSSMigrationModal.svelte @@ -88,14 +88,15 @@ } for (const [key, value] of migrations) { - if (cssString.includes(`${key} {` || `${key}{`)) { + if (cssString.includes(`${key} {`) || cssString.includes(`${key}{`)) { // append value to existing value const regex = new RegExp(`\\${key}\\s*{\\s*([\\s\\S]*?)\\s*}`, 'g') const match = regex.exec(cssString) if (match) { - const existingValue = match[1] + // CSS allows the last declaration to omit its `;`; appending after it needs one. + const existingValue = match[1] && !match[1].endsWith(';') ? `${match[1]};` : match[1] cssString = cssString.replace( regex, diff --git a/frontend/src/lib/components/apps/editor/settingsPanel/inputEditor/EvalV2InputEditor.svelte b/frontend/src/lib/components/apps/editor/settingsPanel/inputEditor/EvalV2InputEditor.svelte index 76ec4413c9..ef25580bc8 100644 --- a/frontend/src/lib/components/apps/editor/settingsPanel/inputEditor/EvalV2InputEditor.svelte +++ b/frontend/src/lib/components/apps/editor/settingsPanel/inputEditor/EvalV2InputEditor.svelte @@ -84,7 +84,7 @@ <Drawer placement="bottom" on:close={() => (fullscreen = false)} - open + bind:open={fullscreen} offset={zIndexes.monacoEditor} > <Splitpanes horizontal class="h-full"> 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 f741f5511d..4a042a9aa9 100644 --- a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/RunnableSelector.svelte +++ b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/RunnableSelector.svelte @@ -201,7 +201,7 @@ {#if rawApps && !onlyFlow} <Tab value="workspaceagents" label="AI agents" icon={Bot} /> {/if} - {#if $roleCaps.apps !== 'compose'} + {#if $roleCaps.code} {#if !onlyFlow} <Tab value="hubscripts" label="Hub scripts" icon={Globe2} /> {/if} diff --git a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/WorkspaceScriptList.svelte b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/WorkspaceScriptList.svelte index 13447c4787..3680879c88 100644 --- a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/WorkspaceScriptList.svelte +++ b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/WorkspaceScriptList.svelte @@ -6,7 +6,7 @@ import SearchItems from '$lib/components/SearchItems.svelte' import NoItemFound from '$lib/components/home/NoItemFound.svelte' import RowIcon from '$lib/components/common/table/RowIcon.svelte' - import { type Script, ScriptService } from '$lib/gen' + import { type ListableScript, ScriptService } from '$lib/gen' import { emptyString } from '$lib/utils' import { Skeleton } from '$lib/components/common' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' @@ -20,8 +20,8 @@ let { filter = $bindable(''), children }: Props = $props() - let scripts: Script[] | undefined = $state(undefined) - let filteredItems: (Script & { marked?: string })[] = $state([]) + let scripts: ListableScript[] | undefined = $state(undefined) + let filteredItems: (ListableScript & { marked?: string })[] = $state([]) let prefilteredItems = $derived(scripts ?? []) const dispatch = createEventDispatcher() diff --git a/frontend/src/lib/components/apps/svelte-grid/MoveResize.svelte b/frontend/src/lib/components/apps/svelte-grid/MoveResize.svelte index 15c98ef83c..6f38d3f74b 100644 --- a/frontend/src/lib/components/apps/svelte-grid/MoveResize.svelte +++ b/frontend/src/lib/components/apps/svelte-grid/MoveResize.svelte @@ -368,7 +368,8 @@ ? intersectingElement?.querySelector('.svlt-grid-container') : document.getElementById('root-grid') - const xPerPxComputed = Number(container?.getAttribute('data-xperpx')) ?? xPerPx + const xPerPxAttr = container?.getAttribute('data-xperpx') + const xPerPxComputed = xPerPxAttr != null ? Number(xPerPxAttr) : xPerPx const position = computePosition( clientX, diff --git a/frontend/src/lib/components/assets/AssetGraph/AssetGraphCanvas.svelte b/frontend/src/lib/components/assets/AssetGraph/AssetGraphCanvas.svelte index e46d761671..f4d339f7ae 100644 --- a/frontend/src/lib/components/assets/AssetGraph/AssetGraphCanvas.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/AssetGraphCanvas.svelte @@ -1,4 +1,5 @@ <script lang="ts"> + import HostWindow from '$lib/components/common/HostWindow.svelte' import '@xyflow/svelte/dist/base.css' import { randomUUID } from '$lib/utils/uuid' import { onMount } from 'svelte' @@ -2310,6 +2311,8 @@ if (paneMenu && !(e.target as HTMLElement | null)?.closest('[data-pane-menu]')) paneMenu = undefined }} +/> +<HostWindow onkeydown={(e) => { if (e.key === 'Escape') paneMenu = undefined }} diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineInsertMenu.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineInsertMenu.svelte index f93826d98f..09735b044e 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineInsertMenu.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineInsertMenu.svelte @@ -64,7 +64,7 @@ loadDefaultScheduleAdvanced, scheduleAdvancedCfg } from '$lib/components/triggers/schedules/ScheduleAdvancedOptions.svelte' - import { workspaceStore } from '$lib/stores' + import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { ArrowLeft, ChevronDown, CornerDownLeft, Loader2 } from 'lucide-svelte' import { tick, untrack } from 'svelte' import { arrowTabNav } from '$lib/attachments/arrowTabNav' @@ -100,6 +100,8 @@ onSchedule }: Props = $props() + const operatingWorkspace = useOperatingWorkspace() + // When there's only one trigger kind, hide the Trigger column entirely // and pre-select it so the user lands directly on the Language picker. const singleKind = $derived(kinds.length === 1 ? kinds[0] : undefined) @@ -170,7 +172,7 @@ // 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 + const ws = $operatingWorkspace if (!ws || config.advancedDefaults !== 'unloaded') return const target = config target.advancedDefaults = 'loading' @@ -619,7 +621,7 @@ overwrite a handler picked while they load. --> {#if config.advancedDefaults === 'loaded'} <ScheduleAdvancedOptions - wsId={$workspaceStore} + wsId={$operatingWorkspace} itemKind="script" canWrite bind:errorHandler={config.advanced.errorHandler} diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineTriggerEditors.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineTriggerEditors.svelte index d8d19845fa..91431f8271 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineTriggerEditors.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineTriggerEditors.svelte @@ -1,6 +1,5 @@ <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, PipelineTriggerDraftKind } from './types' import type { Schedule } from '$lib/gen' @@ -132,8 +131,9 @@ } as Schedule, onSave ) - if (saved || !$workspaceStore) return open({}) - return loadDefaultScheduleAdvanced($workspaceStore) + const workspace = triggerWorkspace ?? $operatingWorkspace + if (saved || !workspace) return open({}) + return loadDefaultScheduleAdvanced(workspace) .then((a) => open(scheduleAdvancedCfg(a))) .catch(() => open({})) } diff --git a/frontend/src/lib/components/common/EditableInput.svelte b/frontend/src/lib/components/common/EditableInput.svelte index fb89fda799..bcf97fe201 100644 --- a/frontend/src/lib/components/common/EditableInput.svelte +++ b/frontend/src/lib/components/common/EditableInput.svelte @@ -127,7 +127,7 @@ this component just proposes new values. {#if editing} <span - class="input-sizer inline-grid items-center {textClass} {className}" + class="input-sizer inline-grid grid-cols-[minmax(0,1fr)] min-w-0 items-center {textClass} {className}" data-value={draft || placeholder} > <TextInput @@ -162,9 +162,11 @@ this component just proposes new values. <style> .input-sizer::after { - content: attr(data-value) ' '; + /* Must measure exactly as wide as the idle button, or siblings move on toggle. */ + content: attr(data-value); visibility: hidden; white-space: pre; + overflow: hidden; grid-area: 1 / 1; font: inherit; padding: 2px; diff --git a/frontend/src/lib/components/common/HostWindow.svelte b/frontend/src/lib/components/common/HostWindow.svelte new file mode 100644 index 0000000000..4d70f57ecc --- /dev/null +++ b/frontend/src/lib/components/common/HostWindow.svelte @@ -0,0 +1,19 @@ +<script lang="ts"> + import type { KeyboardEventHandler } from 'svelte/elements' + import { overlayHostActive } from './overlayHost.svelte' + + type KeyHandler = KeyboardEventHandler<Window> + + // Use this instead of `<svelte:window onkeydown>` in anything that can render inside a + // session preview tab: hidden tabs stay mounted, and their window listeners would + // otherwise act on an editor the user cannot see. + let { onkeydown, onkeydowncapture }: { onkeydown?: KeyHandler; onkeydowncapture?: KeyHandler } = + $props() + + const hostActive = overlayHostActive() +</script> + +<svelte:window + onkeydown={(e) => hostActive() && onkeydown?.(e)} + onkeydowncapture={(e) => hostActive() && onkeydowncapture?.(e)} +/> diff --git a/frontend/src/lib/components/common/button/Button.svelte b/frontend/src/lib/components/common/button/Button.svelte index 9a3b9fe6ac..e514c0686f 100644 --- a/frontend/src/lib/components/common/button/Button.svelte +++ b/frontend/src/lib/components/common/button/Button.svelte @@ -516,9 +516,11 @@ 'rounded-md m-0 p-0 center-center h-full', variant === 'border' ? 'border-0 border-r border-y ' : 'border-0', 'rounded-r-md !rounded-l-none', - size === 'xs2' || size === 'xs' || unifiedSize === 'md' || unifiedSize === 'sm' - ? '!w-8' - : '!w-10', + unifiedSize === 'xs' || unifiedSize === '2xs' + ? '!w-6' + : size === 'xs2' || size === 'xs' || unifiedSize === 'md' || unifiedSize === 'sm' + ? '!w-8' + : '!w-10', dropdownBtnClasses )} > diff --git a/frontend/src/lib/components/common/button/CopyButton.svelte b/frontend/src/lib/components/common/button/CopyButton.svelte index 4eaed95b9b..0371a54b42 100644 --- a/frontend/src/lib/components/common/button/CopyButton.svelte +++ b/frontend/src/lib/components/common/button/CopyButton.svelte @@ -9,7 +9,8 @@ value, sendToast = false, title = 'Copy to clipboard', - class: className = '' + class: className = '', + btnClasses = '' }: { value: string // Also pop the global "copied to clipboard" toast on success. @@ -18,6 +19,7 @@ // always takes over after a copy. title?: string class?: string + btnClasses?: string } = $props() let copied = $state(false) @@ -41,4 +43,5 @@ : { icon: Copy }} onClick={copy} wrapperClasses={className} + {btnClasses} /> diff --git a/frontend/src/lib/components/common/confirmationModal/ConfirmationModal.svelte b/frontend/src/lib/components/common/confirmationModal/ConfirmationModal.svelte index 4b419536fc..3ecb6a93f1 100644 --- a/frontend/src/lib/components/common/confirmationModal/ConfirmationModal.svelte +++ b/frontend/src/lib/components/common/confirmationModal/ConfirmationModal.svelte @@ -1,7 +1,11 @@ <script lang="ts"> import { classNames } from '$lib/utils' import ConditionalPortal from '$lib/components/common/drawer/ConditionalPortal.svelte' - import { getOverlayHost, overlayHostActive } from '$lib/components/common/overlayHost.svelte' + import { + getOverlayHost, + overlayHostActive, + overlayShown + } from '$lib/components/common/overlayHost.svelte' import { createEventDispatcher, type Snippet } from 'svelte' import { fade } from 'svelte/transition' import Button from '../button/Button.svelte' @@ -31,6 +35,9 @@ alwaysPortal?: boolean /** For a notice with nothing to decide: the confirm button is the only one. */ hideCancel?: boolean + /** A third way out, drawn between Cancel and the confirm button. */ + extraAction?: Snippet + cancelVariant?: 'default' | 'subtle' children?: Snippet onConfirmed?: () => void | Promise<void> onCanceled?: () => void @@ -50,6 +57,8 @@ zIndexClass = 'z-[9999]', alwaysPortal = false, hideCancel = false, + extraAction, + cancelVariant = 'default', children, onConfirmed, onCanceled @@ -65,9 +74,12 @@ const posClass = $derived(hostEl ? 'absolute' : 'fixed') const hostActive = overlayHostActive() + const shown = overlayShown() const dispatch = createEventDispatcher() + let extraActionEl = $state<HTMLElement>() + function onKeyDown(event: KeyboardEvent) { // Hidden hosts stay mounted and still receive window keys — see overlayHost. if (!hostActive()) return @@ -93,6 +105,9 @@ // A popover needs Enter both to open from its trigger and to choose from its // content, so leave it alone whether or not it is open. if (popover) return + // Focused, the extra action's button takes Enter itself: confirming here would do + // the opposite of what it says. + if (extraActionEl?.contains(event.target as Node)) return event.stopPropagation() event.preventDefault() if (loading || confirmDisabled) break @@ -119,7 +134,6 @@ const theme = { danger: { Icon: AlertTriangle, - color: 'red', classes: { icon: 'text-red-500 dark:text-red-400', iconWrapper: 'bg-red-100 dark:bg-red-800/50' @@ -128,7 +142,6 @@ reload: { Icon: RefreshCcw, - color: 'dark', classes: { icon: 'text-blue-700 dark:text-blue-300', iconWrapper: 'bg-blue-100 dark:bg-blue-800/50' @@ -139,7 +152,6 @@ // an import. The confirm button stays a plain accent (see `destructive` below). info: { Icon: Info, - color: 'blue', classes: { icon: 'text-blue-700 dark:text-blue-300', iconWrapper: 'bg-blue-100 dark:bg-blue-800/50' @@ -156,7 +168,7 @@ target={hostEl} class={hostEl ? 'contents' : undefined} > - {#if open} + {#if open && shown()} <div transition:fadeFast|local class={twMerge(posClass, 'top-0 bottom-0 left-0 right-0', zIndexClass)} @@ -220,8 +232,7 @@ <Button disabled={loading || confirmDisabled} on:click={() => (dispatch('confirmed'), onConfirmed?.())} - color={theme[type].color} - size="sm" + unifiedSize="sm" shortCut={{ Icon: CornerDownLeft, hide: !keyListen, withoutModifier: true }} variant="accent" destructive={type === 'danger'} @@ -231,12 +242,15 @@ {/if} <span class="min-w-20">{confirmationText} </span> </Button> + {#if extraAction} + <div bind:this={extraActionEl}>{@render extraAction()}</div> + {/if} {#if !hideCancel} <Button disabled={loading} on:click={() => (dispatch('canceled'), onCanceled?.())} - variant="default" - size="sm" + variant={cancelVariant} + unifiedSize="sm" shortCut={{ key: 'Esc', hide: !keyListen, withoutModifier: true }} > Cancel diff --git a/frontend/src/lib/components/common/confirmationModal/DraftSyncConflictModal.svelte b/frontend/src/lib/components/common/confirmationModal/DraftSyncConflictModal.svelte index ca467fd571..8a2f0e4f79 100644 --- a/frontend/src/lib/components/common/confirmationModal/DraftSyncConflictModal.svelte +++ b/frontend/src/lib/components/common/confirmationModal/DraftSyncConflictModal.svelte @@ -55,7 +55,13 @@ } </script> -<Modal2 bind:isOpen title="Draft out of sync" fixedWidth="sm" fixedHeight="adaptive"> +<Modal2 + bind:isOpen + title="Draft out of sync" + fixedWidth="sm" + fixedHeight="adaptive" + closeOnOutsideClick={false} +> <div class="flex flex-col w-full gap-4"> <div class="flex gap-3 items-start flex-1"> <AlertTriangle size={20} class="text-yellow-500 shrink-0 mt-0.5" /> @@ -64,6 +70,7 @@ Another tab, browser, or AI agent saved a newer version of this draft. Your autosave was rejected to avoid overwriting their work. </p> + <p class="text-xs text-secondary break-all">{query.path}</p> {#if conflictHandle.conflict} <p class="text-xs text-secondary"> Server timestamp: {new Date(conflictHandle.conflict.serverTimestamp).toLocaleString()} @@ -75,16 +82,16 @@ <div class="flex justify-end gap-2"> <Button variant="default" - size="sm" + unifiedSize="sm" disabled={busy} on:click={() => UserDraftDbSyncer.clearConflict(query)} > Dismiss </Button> - <Button variant="default" size="sm" disabled={busy} on:click={overwriteServer}> + <Button variant="default" unifiedSize="sm" disabled={busy} on:click={overwriteServer}> Overwrite the remote </Button> - <Button variant="accent" size="sm" loading={busy} on:click={loadFromServer}> + <Button variant="accent" unifiedSize="sm" loading={busy} on:click={loadFromServer}> Load from server </Button> </div> diff --git a/frontend/src/lib/components/common/confirmationModal/OtherUsersDraftsModal.svelte b/frontend/src/lib/components/common/confirmationModal/OtherUsersDraftsModal.svelte index b6ec78f336..f101b22e26 100644 --- a/frontend/src/lib/components/common/confirmationModal/OtherUsersDraftsModal.svelte +++ b/frontend/src/lib/components/common/confirmationModal/OtherUsersDraftsModal.svelte @@ -17,7 +17,7 @@ import { fetchDeployedValueForDiff } from '$lib/components/otherUserDraftDiff' import { OtherUserDraftLoad } from '$lib/components/otherUserDraftLoad.svelte' import { displayDate } from '$lib/utils' - import { userStore } from '$lib/stores' + import { useActingUser } from '$lib/actingUser.svelte' import { armRestartOnFirstInteraction } from '$lib/userDraftToast' import { UserDraft } from '$lib/userDraft.svelte' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' @@ -65,7 +65,8 @@ // 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) + const actingUser = useActingUser(() => workspace) + const isAdmin = $derived(!!actingUser.current?.is_admin || !!actingUser.current?.is_super_admin) async function deleteDraft(target: OtherDraftUser | 'all') { const username = target === 'all' ? undefined : target.username diff --git a/frontend/src/lib/components/common/contextmenu/ContextMenu.svelte b/frontend/src/lib/components/common/contextmenu/ContextMenu.svelte index 49421e78b3..73f8c57a41 100644 --- a/frontend/src/lib/components/common/contextmenu/ContextMenu.svelte +++ b/frontend/src/lib/components/common/contextmenu/ContextMenu.svelte @@ -1,6 +1,6 @@ <script lang="ts"> import { createContextMenu, melt } from '@melt-ui/svelte' - import { overlayPortalTarget } from '$lib/components/common/overlayHost.svelte' + import { overlayPortalTarget, overlayShown } from '$lib/components/common/overlayHost.svelte' import { fly } from 'svelte/transition' import { twMerge } from 'tailwind-merge' import { untrack, type Snippet } from 'svelte' @@ -49,6 +49,7 @@ // Overlays belong to the enclosing pane when there is one — see overlayHost. const hostPortal = overlayPortalTarget('body') + const shown = overlayShown() const { elements: { menu: menuElement, item, trigger }, @@ -111,7 +112,7 @@ {@render children?.()} </div> -{#if $open} +{#if $open && shown()} <div class="{getContextMenuContainerClass(zIndex)} {CONTEXT_MENU_ANIMATION_CLASSES}" use:melt={$menuElement} diff --git a/frontend/src/lib/components/common/modal/Modal.svelte b/frontend/src/lib/components/common/modal/Modal.svelte index 4932349787..399a270a37 100644 --- a/frontend/src/lib/components/common/modal/Modal.svelte +++ b/frontend/src/lib/components/common/modal/Modal.svelte @@ -14,6 +14,7 @@ import { getOverlayHost, overlayHostActive, + overlayShown, setTopmostSurface } from '$lib/components/common/overlayHost.svelte' @@ -108,6 +109,9 @@ const hostEl = $derived(overlayHost?.el()) const posClass = $derived(hostEl ? 'absolute' : 'fixed') const hostActive = overlayHostActive() + // The whole dialog, its place on the overlay stack included, goes while it is not drawn: + // other pages read that stack to decide whether an Escape is theirs. + const shown = overlayShown() // A trail of one level is the dialog at its root, which the plain title already shows. const crumbs = $derived(trail && trail.length > 1 ? trail : undefined) @@ -186,175 +190,177 @@ </h3> {/snippet} -<Disposable bind:open bind:this={disposable} preventEscape {minZIndex}> - {#snippet children({ zIndex })} - <!-- Always portalled, as Drawer is: rendered in place, any `transform`, `filter` or - `overflow` on an ancestor confines the dialog and the nav rail paints over it. --> - <ConditionalPortal condition target={hostEl} class={hostEl ? 'contents' : undefined}> - {#if open} - <!-- svelte-ignore a11y_click_events_have_key_events --> - <!-- svelte-ignore a11y_no_noninteractive_element_interactions --> - <div - onclick={() => (open = false)} - transition:fadeFast|local - class="{posClass} top-0 bottom-0 left-0 right-0" - style="z-index: {zIndex}" - role="dialog" - tabindex="-1" - > +{#if shown()} + <Disposable bind:open bind:this={disposable} preventEscape {minZIndex}> + {#snippet children({ zIndex })} + <!-- Always portalled, as Drawer is: rendered in place, any `transform`, `filter` or + `overflow` on an ancestor confines the dialog and the nav rail paints over it. --> + <ConditionalPortal condition target={hostEl} class={hostEl ? 'contents' : undefined}> + {#if open} + <!-- svelte-ignore a11y_click_events_have_key_events --> + <!-- svelte-ignore a11y_no_noninteractive_element_interactions --> <div - class={twMerge( - posClass, - 'inset-0 bg-gray-500 bg-opacity-75 transition-opacity', - open ? 'ease-out duration-300 opacity-100' : 'ease-in duration-200 opacity-0' - )} - ></div> - - <div class="{posClass} inset-0 z-10 overflow-y-auto"> + onclick={() => (open = false)} + transition:fadeFast|local + class="{posClass} top-0 bottom-0 left-0 right-0" + style="z-index: {zIndex}" + role="dialog" + tabindex="-1" + > <div - class="flex {fillHeight || fitHeight - ? 'h-full' - : 'min-h-full'} items-center justify-center p-4" - > - <!-- svelte-ignore a11y_no_static_element_interactions --> + class={twMerge( + posClass, + 'inset-0 bg-gray-500 bg-opacity-75 transition-opacity', + open ? 'ease-out duration-300 opacity-100' : 'ease-in duration-200 opacity-0' + )} + ></div> + + <div class="{posClass} inset-0 z-10 overflow-y-auto"> <div - onclick={stopPropagation(bubble('click'))} - class={twMerge( - 'relative transform overflow-hidden rounded-md bg-surface px-4 pt-5 pb-4 text-left shadow-xl transition-all sm:w-full sm:max-w-lg sm:p-6', - // The margins are what keeps a content-sized dialog off the viewport edges; a - // filling or fitting one takes its inset from the wrapper's padding instead. - // Fitting is a grid, not a flex column: a grid row gives the body a definite - // height while the dialog still hugs its content, so `h-full` resolves in it. - // The column's 0 minimum is the grid's `min-w-0`: long unbreakable content - // would otherwise widen it past the dialog. - fillHeight - ? 'h-full flex flex-col' - : fitHeight - ? kind == 'button' - ? 'max-h-full grid grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_auto]' - : 'max-h-full grid grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)]' - : 'sm:my-8', - c, - open - ? 'ease-out duration-300 opacity-100 translate-y-0 sm:scale-100' - : 'ease-in duration-200 opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95' - )} - {style} + class="flex {fillHeight || fitHeight + ? 'h-full' + : 'min-h-full'} items-center justify-center p-4" > - {#if kind == 'X'} - <div class="absolute top-4 right-4" - ><CloseButton on:close={() => (open = false)} /></div - > - {/if} - <div class="flex {fillHeight ? 'flex-1 min-h-0' : fitHeight ? 'min-h-0' : ''}"> - <!-- min-w-0: without it this flex item takes its content's min-content width and - stretches the modal past its max-width instead of letting content shrink. --> - <div - class="text-left flex-1 min-w-0 {fillHeight || fitHeight - ? 'flex flex-col min-h-0' - : ''}" - > - <!-- pr-8 under `kind="X"`: the close button is absolutely positioned, so a long - heading or the header actions would otherwise run under it. --> + <!-- svelte-ignore a11y_no_static_element_interactions --> + <div + onclick={stopPropagation(bubble('click'))} + class={twMerge( + 'relative transform overflow-hidden rounded-md bg-surface px-4 pt-5 pb-4 text-left shadow-xl transition-all sm:w-full sm:max-w-lg sm:p-6', + // The margins are what keeps a content-sized dialog off the viewport edges; a + // filling or fitting one takes its inset from the wrapper's padding instead. + // Fitting is a grid, not a flex column: a grid row gives the body a definite + // height while the dialog still hugs its content, so `h-full` resolves in it. + // The column's 0 minimum is the grid's `min-w-0`: long unbreakable content + // would otherwise widen it past the dialog. + fillHeight + ? 'h-full flex flex-col' + : fitHeight + ? kind == 'button' + ? 'max-h-full grid grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_auto]' + : 'max-h-full grid grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)]' + : 'sm:my-8', + c, + open + ? 'ease-out duration-300 opacity-100 translate-y-0 sm:scale-100' + : 'ease-in duration-200 opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95' + )} + {style} + > + {#if kind == 'X'} + <div class="absolute top-4 right-4" + ><CloseButton on:close={() => (open = false)} /></div + > + {/if} + <div class="flex {fillHeight ? 'flex-1 min-h-0' : fitHeight ? 'min-h-0' : ''}"> + <!-- min-w-0: without it this flex item takes its content's min-content width and + stretches the modal past its max-width instead of letting content shrink. --> <div - class="flex flex-row items-start justify-between gap-2 min-w-0 {kind === 'X' - ? 'pr-8' + class="text-left flex-1 min-w-0 {fillHeight || fitHeight + ? 'flex flex-col min-h-0' : ''}" > - {#if crumbs && current} - <div class="flex flex-row items-start gap-1 min-w-0"> - {#if back?.onclick} - <!-- Pulled left so the heading lands about where the title sits at the - root, and up so it reads against that heading rather than against - the two lines together. --> - <Button - variant="subtle" - unifiedSize="sm" - iconOnly - startIcon={{ icon: ChevronLeft }} - title="Back to {back.label}" - onClick={back.onclick} - wrapperClasses="shrink-0 -ml-1 -mt-0.5" - /> - {/if} - <div class="flex flex-col min-w-0"> - {@render heading(current.label, levelBadge, true)} - <!-- The way back in full: the control above carries one level of it. --> - <nav - aria-label="Breadcrumb" - class="flex flex-row items-center gap-0.5 min-w-0 text-xs text-secondary" - > - {#each crumbs.slice(0, -1) as segment, i (i)} - {#if i > 0} - <span class="flex shrink-0" in:fade={{ duration: 150 }}> - <ChevronRight size={12} class="text-tertiary shrink-0" /> - </span> - {/if} - {#if segment.onclick} - <Button - variant="subtle" - unifiedSize="2xs" - onClick={segment.onclick} - wrapperClasses="min-w-0 shrink" - btnClasses="!px-0 !font-normal !text-xs text-secondary hover:text-emphasis hover:underline hover:!bg-transparent min-w-0" - > - <span class="truncate">{segment.label}</span> - </Button> - {:else} - <span class="truncate" in:fade={{ duration: 150 }} - >{segment.label}</span - > - {/if} - {#if i === 0} - {@render titleBadge?.()} - {/if} - {/each} - </nav> + <!-- pr-8 under `kind="X"`: the close button is absolutely positioned, so a long + heading or the header actions would otherwise run under it. --> + <div + class="flex flex-row items-start justify-between gap-2 min-w-0 {kind === 'X' + ? 'pr-8' + : ''}" + > + {#if crumbs && current} + <div class="flex flex-row items-start gap-1 min-w-0"> + {#if back?.onclick} + <!-- Pulled left so the heading lands about where the title sits at the + root, and up so it reads against that heading rather than against + the two lines together. --> + <Button + variant="subtle" + unifiedSize="sm" + iconOnly + startIcon={{ icon: ChevronLeft }} + title="Back to {back.label}" + onClick={back.onclick} + wrapperClasses="shrink-0 -ml-1 -mt-0.5" + /> + {/if} + <div class="flex flex-col min-w-0"> + {@render heading(current.label, levelBadge, true)} + <!-- The way back in full: the control above carries one level of it. --> + <nav + aria-label="Breadcrumb" + class="flex flex-row items-center gap-0.5 min-w-0 text-xs text-secondary" + > + {#each crumbs.slice(0, -1) as segment, i (i)} + {#if i > 0} + <span class="flex shrink-0" in:fade={{ duration: 150 }}> + <ChevronRight size={12} class="text-tertiary shrink-0" /> + </span> + {/if} + {#if segment.onclick} + <Button + variant="subtle" + unifiedSize="2xs" + onClick={segment.onclick} + wrapperClasses="min-w-0 shrink" + btnClasses="!px-0 !font-normal !text-xs text-secondary hover:text-emphasis hover:underline hover:!bg-transparent min-w-0" + > + <span class="truncate">{segment.label}</span> + </Button> + {:else} + <span class="truncate" in:fade={{ duration: 150 }} + >{segment.label}</span + > + {/if} + {#if i === 0} + {@render titleBadge?.()} + {/if} + {/each} + </nav> + </div> </div> - </div> - {:else} - {@render heading(title, titleBadge, false)} + {:else} + {@render heading(title, titleBadge, false)} + {/if} + {@render settings?.()} + </div> + + {#if description} + <p class="mt-1 text-xs text-secondary">{description}</p> {/if} - {@render settings?.()} - </div> - {#if description} - <p class="mt-1 text-xs text-secondary">{description}</p> - {/if} - - <!-- `mt-1` when paginated: a page carries its own description as its first line, - and it belongs where the dialog's own sat, right under the title. Fitting, the - body is the scroller of last resort: 4px of padding, taken back by the margins, - keeps the focus rings of controls along its edges from being clipped. --> - <div - class={fitHeight - ? 'mt-3 -mx-1 -mb-1 p-1 flex-1 min-h-0 overflow-y-auto text-sm text-primary' - : `${paginated ? 'mt-1' : 'mt-4'} text-sm text-primary ${fillHeight ? 'flex-1 min-h-0' : ''}`} - > - {@render children_render?.()} + <!-- `mt-1` when paginated: a page carries its own description as its first line, + and it belongs where the dialog's own sat, right under the title. Fitting, the + body is the scroller of last resort: 4px of padding, taken back by the margins, + keeps the focus rings of controls along its edges from being clipped. --> + <div + class={fitHeight + ? 'mt-3 -mx-1 -mb-1 p-1 flex-1 min-h-0 overflow-y-auto text-sm text-primary' + : `${paginated ? 'mt-1' : 'mt-4'} text-sm text-primary ${fillHeight ? 'flex-1 min-h-0' : ''}`} + > + {@render children_render?.()} + </div> </div> </div> + {#if kind == 'button'} + <div class="flex items-center space-x-2 flex-row-reverse space-x-reverse mt-4"> + {@render actions?.()} + <Button + on:click={() => { + dispatch('canceled') + open = false + }} + color="light" + size="sm" + > + {cancelText ?? 'Cancel'} + </Button> + </div> + {/if} </div> - {#if kind == 'button'} - <div class="flex items-center space-x-2 flex-row-reverse space-x-reverse mt-4"> - {@render actions?.()} - <Button - on:click={() => { - dispatch('canceled') - open = false - }} - color="light" - size="sm" - > - {cancelText ?? 'Cancel'} - </Button> - </div> - {/if} </div> </div> </div> - </div> - {/if} - </ConditionalPortal> - {/snippet} -</Disposable> + {/if} + </ConditionalPortal> + {/snippet} + </Disposable> +{/if} diff --git a/frontend/src/lib/components/common/modal/Modal2.svelte b/frontend/src/lib/components/common/modal/Modal2.svelte index 4c76c4f935..3d9a96984c 100644 --- a/frontend/src/lib/components/common/modal/Modal2.svelte +++ b/frontend/src/lib/components/common/modal/Modal2.svelte @@ -9,7 +9,7 @@ import List from '$lib/components/common/layout/List.svelte' import { fade } from 'svelte/transition' import Disposable from '../drawer/Disposable.svelte' - import { overlayHostActive, setTopmostSurface } from '../overlayHost.svelte' + import { overlayHostActive, overlayShown, setTopmostSurface } from '../overlayHost.svelte' import { untrack } from 'svelte' interface Props { @@ -94,6 +94,9 @@ // at that drawer do not close the dialog underneath. let disposable: Disposable | undefined = $state(undefined) const hostActive = overlayHostActive() + // The whole dialog, its place on the overlay stack included, goes while it is not drawn: + // other pages read that stack to decide whether an Escape is theirs. + const shown = overlayShown() setTopmostSurface(() => disposable?.isTopmost() ?? true) $effect(() => { isOpen @@ -135,80 +138,82 @@ }} /> -<Disposable bind:open={isOpen} bind:this={disposable} preventEscape> - {#snippet children({ zIndex })} - {#if isOpen} - <Portal name="always-mounted" {target}> - <div - class={'fixed top-0 bottom-0 left-0 right-0 transition-all overflow-auto bg-black bg-opacity-60 w-full h-full'} - style="z-index: {zIndex}" - transition:fadeFast|local - > - <div class="flex min-h-full items-center justify-center p-8"> - <div - style={`width: ${widthMap[fixedWidth]}; ${ - heightMap[fixedHeight] ? `height: ${heightMap[fixedHeight]}; ` : '' - }${css?.popup?.style || ''}`} - class={twMerge( - 'max-h-screen-80 max-w-screen-80 rounded-lg relative bg-surface', - formStyling ? 'py-4 px-6' : 'p-4', - css?.popup?.class, - 'wm-modal-form-popup' - )} - use:clickOutside={{ - onClickOutside: () => - closeOnOutsideClick && !preventDismiss && topmostAtPress && close(), - // A dropdown opened from inside the dialog portals its menu out of it, so a - // click on one of its items lands outside this node and would close the - // dialog under the menu. - exclude: async () => - Array.from(document.querySelectorAll('[data-menu]')) as HTMLElement[] - }} - > - <List gap="md"> - <div class="flex w-full"> - <List horizontal justify="between"> - <h3 class={formStyling ? 'font-semibold' : undefined}>{title}</h3> - <div class="grow w-min-0"> - <List horizontal justify="between"> - <div class="min-w-0 grow"> - {@render headerLeft?.()} - </div> - <div class="min-w-0 grow-0 justify-end"> - <List horizontal justify="end"> - {@render headerRight?.()} - <div class="w-8"> - <button - id="modal-close-button" - disabled={preventDismiss} - onclick={() => { - close() - }} - class="hover:bg-surface-hover rounded-full w-8 h-8 flex items-center justify-center transition-all disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent" - > - <X class="text-primary " /> - </button> - </div> - </List> - </div> - </List> - </div> - </List> - </div> +{#if shown()} + <Disposable bind:open={isOpen} bind:this={disposable} preventEscape> + {#snippet children({ zIndex })} + {#if isOpen} + <Portal name="always-mounted" {target}> + <div + class={'fixed top-0 bottom-0 left-0 right-0 transition-all overflow-auto bg-black bg-opacity-60 w-full h-full'} + style="z-index: {zIndex}" + transition:fadeFast|local + > + <div class="flex min-h-full items-center justify-center p-8"> + <div + style={`width: ${widthMap[fixedWidth]}; ${ + heightMap[fixedHeight] ? `height: ${heightMap[fixedHeight]}; ` : '' + }${css?.popup?.style || ''}`} + class={twMerge( + 'max-h-screen-80 max-w-screen-80 rounded-lg relative bg-surface', + formStyling ? 'py-4 px-6' : 'p-4', + css?.popup?.class, + 'wm-modal-form-popup' + )} + use:clickOutside={{ + onClickOutside: () => + closeOnOutsideClick && !preventDismiss && topmostAtPress && close(), + // A dropdown opened from inside the dialog portals its menu out of it, so a + // click on one of its items lands outside this node and would close the + // dialog under the menu. + exclude: async () => + Array.from(document.querySelectorAll('[data-menu]')) as HTMLElement[] + }} + > + <List gap="md"> + <div class="flex w-full"> + <List horizontal justify="between"> + <h3 class={formStyling ? 'font-semibold' : undefined}>{title}</h3> + <div class="grow w-min-0"> + <List horizontal justify="between"> + <div class="min-w-0 grow"> + {@render headerLeft?.()} + </div> + <div class="min-w-0 grow-0 justify-end"> + <List horizontal justify="end"> + {@render headerRight?.()} + <div class="w-8"> + <button + id="modal-close-button" + disabled={preventDismiss} + onclick={() => { + close() + }} + class="hover:bg-surface-hover rounded-full w-8 h-8 flex items-center justify-center transition-all disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent" + > + <X class="text-primary " /> + </button> + </div> + </List> + </div> + </List> + </div> + </List> + </div> - <!-- svelte-ignore a11y_click_events_have_key_events --> - <!-- svelte-ignore a11y_no_static_element_interactions --> - <div - class="w-full flex grow min-h-0 {contentClasses}" - onclick={stopPropagation(() => {})} - > - {@render body?.()} - </div> - </List> + <!-- svelte-ignore a11y_click_events_have_key_events --> + <!-- svelte-ignore a11y_no_static_element_interactions --> + <div + class="w-full flex grow min-h-0 {contentClasses}" + onclick={stopPropagation(() => {})} + > + {@render body?.()} + </div> + </List> + </div> </div> </div> - </div> - </Portal> - {/if} - {/snippet} -</Disposable> + </Portal> + {/if} + {/snippet} + </Disposable> +{/if} diff --git a/frontend/src/lib/components/common/overlayHost.svelte.ts b/frontend/src/lib/components/common/overlayHost.svelte.ts index 824e239519..da12483392 100644 --- a/frontend/src/lib/components/common/overlayHost.svelte.ts +++ b/frontend/src/lib/components/common/overlayHost.svelte.ts @@ -80,6 +80,21 @@ export function overlayHostActive(): () => boolean { return () => host?.active() ?? true } +/** + * Whether this component's overlay is drawn. An overlay anchored to its host's element hides + * with it; a host without one leaves its overlays on the viewport, where one left open while + * the host is hidden would cover whatever the user went to. That overlay is not rendered + * until the host is back, rather than hidden: an open drawer stays on its stack, an open + * popover keeps its focus trap, and other pages stop handling keys while any + * `[role="dialog"]` is in the document. + * + * Reads context, so call it during component initialisation. + */ +export function overlayShown(): () => boolean { + const host = getOverlayHost() + return () => !host || host.active() || !!host.el() +} + const TOPMOST_SURFACE_KEY = 'topmostSurface' /** diff --git a/frontend/src/lib/components/common/sidebar/SidebarNavigation.svelte b/frontend/src/lib/components/common/sidebar/SidebarNavigation.svelte index b38fd7e09a..6d368eb410 100644 --- a/frontend/src/lib/components/common/sidebar/SidebarNavigation.svelte +++ b/frontend/src/lib/components/common/sidebar/SidebarNavigation.svelte @@ -5,6 +5,7 @@ import { arrowTabNav } from '$lib/attachments/arrowTabNav' import EEOnly from '$lib/components/EEOnly.svelte' import { enterpriseLicense } from '$lib/stores' + import { ChevronRight } from 'lucide-svelte' interface NavigationItem { id: string @@ -29,10 +30,19 @@ onNavigate: (id: string) => void /** Renders each item as a link to this URL; the link navigates, so `onNavigate` is not called. */ itemHref?: (id: string) => string + /** Ends each entry with a chevron, for a list whose entries each open as a page of their own. */ + drillIn?: boolean class?: string } - let { groups, selectedId, onNavigate, itemHref, class: className = '' }: Props = $props() + let { + groups, + selectedId, + onNavigate, + itemHref, + drillIn = false, + class: className = '' + }: Props = $props() </script> <!-- Up/Down walks the items, wrapping at the ends. On the wrapper rather than on each @@ -58,7 +68,7 @@ aiId={item.aiId} aiDescription={item.aiDescription} startIcon={item.icon ? { icon: item.icon } : undefined} - btnClasses={'!justify-start text-left !w-full'} + btnClasses="group/nav-item !justify-start text-left !w-full" href={itemHref?.(item.id)} onClick={itemHref ? undefined : () => onNavigate(item.id)} > @@ -74,6 +84,14 @@ {item.count} </span> {/if} + {#if drillIn} + <!-- On the hovered or focused entry only; a touch screen cannot hover, so + there it stays on every entry. --> + <ChevronRight + size={14} + class="text-tertiary shrink-0 opacity-0 group-hover/nav-item:opacity-100 group-focus-visible/nav-item:opacity-100 [@media(hover:none)]:opacity-100" + /> + {/if} </div> </Button> {/if} diff --git a/frontend/src/lib/components/common/table/AgentRow.svelte b/frontend/src/lib/components/common/table/AgentRow.svelte index c47e0fd871..4be0fc4459 100644 --- a/frontend/src/lib/components/common/table/AgentRow.svelte +++ b/frontend/src/lib/components/common/table/AgentRow.svelte @@ -5,6 +5,7 @@ import type ShareModal from '$lib/components/ShareModal.svelte' import type DeployWorkspaceDrawer from '$lib/components/DeployWorkspaceDrawer.svelte' import RowLabels from './RowLabels.svelte' + import AskAiRowButton from './AskAiRowButton.svelte' import type { ListableResource } from '$lib/gen' import { roleCapabilities, userStore, workspaceStore } from '$lib/stores' import { createEventDispatcher } from 'svelte' @@ -17,6 +18,7 @@ import { cachedDeployUiSettings, warmDeployUiSettings } from '$lib/components/home/deploy_ui' import Row from './Row.svelte' import { selectMenuItems, type RowSelection } from './rowSelection' + import { roleCanAuthor } from '$lib/editRights' /** * A home-page row for a saved agent. The agent is an `ai_agent` resource, so the row opens the @@ -78,7 +80,9 @@ {keyboardSelected} {marked} path={agent.draft_path ?? agent.path} - summary={agent.description} + summary={agent.is_draft + ? `${agent.description || agent.draft_path || agent.path}*` + : agent.description} workspaceId={agent.workspace_id ?? $workspaceStore ?? ''} canFavorite={!agent.draft_only} {depth} @@ -86,26 +90,30 @@ > {#snippet badges()} <SharedBadge canWrite={agent.canWrite} extraPerms={agent.extra_perms} /> - <RowLabels inherited={agent.inherited_labels} /> + <RowLabels labels={agent.labels} inherited={agent.inherited_labels} /> + <!-- An agent's draft is private, so the only owner to show is the reader. --> <DraftBadge is_draft={agent.is_draft} draft_only={agent.draft_only} + draft_users={agent.is_draft ? [{ username: $userStore?.username }] : []} currentUsername={$userStore?.username} workspace={$workspaceStore ?? undefined} itemKind="resource" + agent path={agent.path} onMigrated={() => dispatch('change')} /> {/snippet} {#snippet actions()} - {#if agent.canWrite} - <span class="hidden md:inline-flex"> + <span class="hidden md:inline-flex"> + <AskAiRowButton kind="agent" path={agent.path} summary={agent.description} /> + {#if agent.canWrite} <Button variant="subtle" unifiedSize="sm" startIcon={{ icon: Pen }} href={editHref}> Edit </Button> - </span> - {/if} + {/if} + </span> <Dropdown size="sm" items={() => [ @@ -117,6 +125,7 @@ draftOnly: Boolean(agent.draft_only), wsSpecific: agent.ws_specific, noCode: !$roleCapabilities.code, + canAuthor: roleCanAuthor('agent', $roleCapabilities), onShare: () => shareModal.openDrawer?.(agent.path, 'resource'), onDeploy: () => deploymentDrawer.openDrawer(agent.path, 'resource'), onHistory: () => history?.open(), diff --git a/frontend/src/lib/components/common/tabs/DraggableTabs.svelte b/frontend/src/lib/components/common/tabs/DraggableTabs.svelte index ae2c4c4bae..1752c81681 100644 --- a/frontend/src/lib/components/common/tabs/DraggableTabs.svelte +++ b/frontend/src/lib/components/common/tabs/DraggableTabs.svelte @@ -6,6 +6,8 @@ /** Hover title. Labels truncate at 180px, so set this whenever the label can * be long enough that two tabs would truncate to the same visible text. */ title?: string + /** Shown after the label and never truncated: a long label ellipsizes before it. */ + labelSuffix?: string /** Optional lucide-svelte (or compatible) component rendered at 12px before the label. */ icon?: any /** Optional class applied to the icon (e.g. `text-accent` to tint it). */ @@ -267,7 +269,14 @@ {#if Icon} <Icon size={12} class={tab.iconClass} /> {/if} - <span class={twMerge('truncate max-w-[180px]', tab.labelClass)}>{tab.label}</span> + {#if tab.labelSuffix} + <span class={twMerge('flex min-w-0 max-w-[180px]', tab.labelClass)}> + <span class="truncate">{tab.label}</span> + <span class="shrink-0 whitespace-pre">{tab.labelSuffix}</span> + </span> + {:else} + <span class={twMerge('truncate max-w-[180px]', tab.labelClass)}>{tab.label}</span> + {/if} {#if tabAccessory} <span class="inline-flex items-center"> {@render tabAccessory(tab, isActive)} @@ -277,7 +286,7 @@ <button type="button" class="opacity-0 group-hover:opacity-100 focus:opacity-100 rounded hover:bg-surface-hover w-4 h-4 inline-flex items-center justify-center" - aria-label={`Close ${tab.label}`} + aria-label={`Close ${tab.label}${tab.labelSuffix ?? ''}`} onclick={(e) => { e.stopPropagation() onClose?.(tab.id) diff --git a/frontend/src/lib/components/copilot/StepGenQuick.svelte b/frontend/src/lib/components/copilot/StepGenQuick.svelte index 3890cacd58..15c04f092b 100644 --- a/frontend/src/lib/components/copilot/StepGenQuick.svelte +++ b/frontend/src/lib/components/copilot/StepGenQuick.svelte @@ -1,6 +1,6 @@ <script lang="ts"> import { copilotInfo } from '$lib/aiStore' - import { ScriptService, type Script } from '$lib/gen' + import { ScriptService, type ListableScript } from '$lib/gen' import { Wand2, Loader2 } from 'lucide-svelte' import SearchItems from '../SearchItems.svelte' @@ -11,14 +11,14 @@ const operatingWorkspace = useOperatingWorkspace() - let scripts: Script[] | undefined = $state(undefined) + let scripts: ListableScript[] | undefined = $state(undefined) interface Props { funcDesc: string trigger?: boolean loading?: boolean preFilter: string disableAi?: boolean - filteredItems?: (Script & { marked?: string })[] | (Item & { marked?: string })[] + filteredItems?: (ListableScript & { marked?: string })[] | (Item & { marked?: string })[] } let { diff --git a/frontend/src/lib/components/copilot/aiProviders.ts b/frontend/src/lib/components/copilot/aiProviders.ts index 5b2abbf040..ae7d559f4f 100644 --- a/frontend/src/lib/components/copilot/aiProviders.ts +++ b/frontend/src/lib/components/copilot/aiProviders.ts @@ -110,17 +110,21 @@ export const AI_PROVIDERS: Record<ChatAIProvider, AIProviderDetails> = { } /** Decision models answer typed questions instead of messages, so only an AI decision offers - * them: TypeSafe's Jev, Cloudflare's Jev-compatible Clef, and the model of OpenAI's Decisions - * API, which an OpenAI resource serves next to its chat models. The pinned Jev version is there - * for flows tuned against its probabilities. */ + * them: TypeSafe's Jev, Cloudflare's Jev-compatible Clef, and the models of OpenAI's and Gemini's + * Decisions APIs, which an OpenAI or Google AI resource serves next to its chat models. The + * pinned Jev version is there for flows tuned against its probabilities. */ export const DECISION_AI_PROVIDERS: Record< - Exclude<AIProvider, ChatAIProvider> | 'openai', + Exclude<AIProvider, ChatAIProvider> | 'openai' | 'googleai', AIProviderDetails > = { openai: { label: 'OpenAI', defaultModels: ['gpt-6-luna'] }, + googleai: { + label: 'Google AI', + defaultModels: ['gemini-decision-1'] + }, typesafe: { label: 'TypeSafe', defaultModels: ['jev-latest', 'jev-1.13.0'] diff --git a/frontend/src/lib/components/copilot/aiResourceProvider.ts b/frontend/src/lib/components/copilot/aiResourceProvider.ts index cd80bb21c0..48d40cbc12 100644 --- a/frontend/src/lib/components/copilot/aiResourceProvider.ts +++ b/frontend/src/lib/components/copilot/aiResourceProvider.ts @@ -1,20 +1,64 @@ import type { AIProvider } from '$lib/gen' import { AI_PROVIDERS } from './lib' -/** A resource type that authenticates the same provider another way, offered as a switch when - * creating a resource of the first, since a picker scoped to a provider only creates its main type. */ -export const AI_RESOURCE_TYPE_ALTERNATIVES: Record<string, { resourceType: string; label: string }> = { - anthropic: { - resourceType: 'anthropic_federated', - label: 'Authenticate with Workload Identity Federation instead of an API key' - }, - anthropic_federated: { resourceType: 'anthropic', label: 'Use an API key instead' } +/** Whether a resource of this type and value reaches Claude or Gemini through Vertex AI with an + * access token it stores, which `vertex_ai_federated` would let it stop storing. */ +export function isTokenVertexResource( + resourceType: string | undefined, + value: Record<string, any> | undefined +): boolean { + return ( + (resourceType === 'anthropic' || resourceType === 'googleai') && + value?.platform === 'google_vertex_ai' + ) } -/** The AI provider a resource of this type holds credentials for, if any. */ -export function aiResourceProvider(resourceType: string | undefined): AIProvider | undefined { +/** A resource type that authenticates the same provider another way, offered as a switch when + * creating a resource of the first, since a picker scoped to a provider only creates its main + * type. `carry` names the fields the switch keeps. */ +export function aiResourceTypeAlternative( + resourceType: string, + value: Record<string, any> | undefined +): { resourceType: string; label: string; carry?: string[] } | undefined { + if (isTokenVertexResource(resourceType, value)) { + return { + resourceType: 'vertex_ai_federated', + label: 'Use Workload Identity Federation instead of an access token', + carry: ['base_url'] + } + } + if (resourceType === 'anthropic') { + return { + resourceType: 'anthropic_federated', + label: 'Authenticate with Workload Identity Federation instead of an API key' + } + } + if (resourceType === 'anthropic_federated') { + return { resourceType: 'anthropic', label: 'Use an API key instead' } + } + return undefined +} + +/** The provider a Vertex AI endpoint serves, read off its `publishers/<publisher>` segment. */ +export function vertexPublisherProvider(baseUrl: unknown): AIProvider | undefined { + if (typeof baseUrl !== 'string') return undefined + if (baseUrl.includes('/publishers/anthropic/')) return 'anthropic' + if (baseUrl.includes('/publishers/google/')) return 'googleai' + return undefined +} + +/** The AI provider a resource of this type holds credentials for, if any. A + * `vertex_ai_federated` resource serves both Claude and Gemini, so its provider is the publisher + * its `base_url` names, Google when it names none yet. */ +export function aiResourceProvider( + resourceType: string | undefined, + value?: Record<string, any> +): AIProvider | undefined { if (resourceType === 'openai_client_credentials_oauth') return 'openai' if (resourceType === 'anthropic_federated') return 'anthropic' + if (resourceType === 'vertex_ai_federated') { + return vertexPublisherProvider(value?.base_url) ?? 'googleai' + } return resourceType && Object.hasOwn(AI_PROVIDERS, resourceType) ? (resourceType as AIProvider) : undefined diff --git a/frontend/src/lib/components/copilot/autocomplete/Autocompletor.ts b/frontend/src/lib/components/copilot/autocomplete/Autocompletor.ts index 5c9519ba1e..ce1f9bc3f2 100644 --- a/frontend/src/lib/components/copilot/autocomplete/Autocompletor.ts +++ b/frontend/src/lib/components/copilot/autocomplete/Autocompletor.ts @@ -9,7 +9,7 @@ import { setGlobalCSS } from '../shared' import { supportsAutocomplete } from '../utils' import { get } from 'svelte/store' import type { MonacoLanguageClient } from 'monaco-languageclient' -import { copilotInfo } from '$lib/aiStore' +import { copilotInfo, type AiTarget } from '$lib/aiStore' import { getTypeScriptWorker } from '@codingame/monaco-vscode-standalone-typescript-language-features' // max ratio of completions to context window @@ -72,15 +72,21 @@ export class Autocompletor { #completionDisposable: IDisposable #cursorDisposable: IDisposable #lastCompletions: string[] = [] - #contextWindow: number = 0 + #sessionTarget: (() => AiTarget | undefined) | undefined #shouldShowDeletionCue = false #languageClient: MonacoLanguageClient | undefined = undefined constructor( editor: meditor.IStandaloneCodeEditor, scriptLang: ScriptLang | 'bunnative' | 'jsx' | 'tsx' | 'json', - options: { workflowAsCode?: boolean } = {} + options: { + workflowAsCode?: boolean + /** Set in an AI session's editor: completions go to the session's workspace with its + * AI config. Undefined while that config is loading. */ + sessionTarget?: () => AiTarget | undefined + } = {} ) { + this.#sessionTarget = options.sessionTarget setGlobalCSS( 'ai-chat-autocomplete', ` @@ -94,15 +100,6 @@ export class Autocompletor { const deletionsCues = editor.createDecorationsCollection() - const { codeCompletionModel: completionModel, contextWindowPerModel } = get(copilotInfo) - this.#contextWindow = completionModel - ? getEffectiveModelContextWindow( - completionModel.provider, - completionModel.model, - contextWindowPerModel - ) - : ASSUMED_CONTEXT_WINDOW - this.#completionDisposable = languages.registerInlineCompletionsProvider( { pattern: '**' }, { @@ -520,9 +517,22 @@ export class Autocompletor { const markers = meditor.getModelMarkers({ resource: model.uri }) const markersAtCursor = this.#markersAtCursor(position, markers) + const target = this.#sessionTarget?.() + // A session's editor completes only once its own workspace's config is known. + if (this.#sessionTarget && !target) { + return + } + const { codeCompletionModel, contextWindowPerModel } = target?.info ?? get(copilotInfo) + const contextWindow = codeCompletionModel + ? getEffectiveModelContextWindow( + codeCompletionModel.provider, + codeCompletionModel.model, + contextWindowPerModel + ) + : ASSUMED_CONTEXT_WINDOW const librariesCompletions: string = completions .join('\n') - .slice(0, Math.floor(this.#contextWindow * COMPLETIONS_MAX_RATIO)) + .slice(0, Math.floor(contextWindow * COMPLETIONS_MAX_RATIO)) const completion = await autocompleteRequest( { @@ -533,7 +543,8 @@ export class Autocompletor { libraries: librariesCompletions, workflowAsCode: this.#workflowAsCode }, - this.#abortController + this.#abortController, + target ) if (!completion) { diff --git a/frontend/src/lib/components/copilot/autocomplete/request.ts b/frontend/src/lib/components/copilot/autocomplete/request.ts index cc3987ebe5..651b212ec2 100644 --- a/frontend/src/lib/components/copilot/autocomplete/request.ts +++ b/frontend/src/lib/components/copilot/autocomplete/request.ts @@ -4,7 +4,7 @@ import { getLangContext } from '../chat/script/core' import { type ScriptLang } from '$lib/gen/types.gen' import type { editor } from 'monaco-editor' import { getCommentSymbol } from '../utils' -import { copilotInfo } from '$lib/aiStore' +import { copilotInfo, type AiTarget } from '$lib/aiStore' function comment(commentSymbol: string, text: string) { return text @@ -22,9 +22,10 @@ export async function autocompleteRequest( libraries: string workflowAsCode?: boolean }, - abortController: AbortController + abortController: AbortController, + target?: AiTarget ) { - const providerModel = get(copilotInfo).codeCompletionModel + const providerModel = (target?.info ?? get(copilotInfo)).codeCompletionModel if (!providerModel) { throw new Error('No code completion model selected') @@ -56,7 +57,8 @@ export async function autocompleteRequest( context.prefix, context.suffix, providerModel, - abortController + abortController, + target?.workspace ) return completion diff --git a/frontend/src/lib/components/copilot/chat/AIChat.svelte b/frontend/src/lib/components/copilot/chat/AIChat.svelte index d59254f02f..18a29fc741 100644 --- a/frontend/src/lib/components/copilot/chat/AIChat.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChat.svelte @@ -10,6 +10,7 @@ import { SUPPORTED_CHAT_SCRIPT_LANGUAGES } from './script/core' import { copilotInfo } from '$lib/aiStore' import type { ComposerSelection } from './composerBox' + import { overlayHostActive } from '$lib/components/common/overlayHost.svelte' let { hideHeader = false, @@ -17,6 +18,7 @@ forceDisabled = false, forceDisabledMessage = '', wideLayout = false, + stickyUserMessage = false, emptyHint, starter = undefined, onSent = undefined, @@ -40,6 +42,7 @@ // columns are centered in a max-w-3xl px-8 box. Sessions opt // in; the narrow global-chat panel leaves it off. wideLayout?: boolean + stickyUserMessage?: boolean emptyHint?: import('svelte').Snippet starter?: import('./starter/starterPrompts.svelte').ChatStarter onSent?: () => void @@ -153,10 +156,15 @@ $effect(() => { aiChatManager.updateMode(untrack(() => aiChatManager.mode)) }) + + // A chat kept mounted while hidden (the sessions page's, on every other page) must leave + // the browser its Cmd+L. + const hostActive = overlayHostActive() </script> <svelte:window onkeydown={(e) => { + if (!hostActive()) return if ((e.ctrlKey || e.metaKey) && e.key === 'l') { e.preventDefault() aiChatDisplay?.focusInput() @@ -212,6 +220,7 @@ {hideHeader} {hideModeSelector} {wideLayout} + {stickyUserMessage} {emptyHint} {starter} {onSent} diff --git a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte index 683a089cd5..5da330d20d 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte @@ -1,10 +1,12 @@ <script lang="ts"> import { createBottomSticker } from '$lib/components/stickToBottom' import AIChatMessage from './AIChatMessage.svelte' + import { messageDraft, segments } from './chatDraft' + import { lineCountLabel } from './pasteTokens' import AppAvailableContextList from './AppAvailableContextList.svelte' import ChatContextPicker from './ChatContextPicker.svelte' import WorkspaceMentionPicker from './WorkspaceMentionPicker.svelte' - import { type Snippet } from 'svelte' + import { flushSync, untrack, type Snippet } from 'svelte' import { AlertTriangle, ArrowDown, @@ -57,6 +59,7 @@ import { chatItemKey, createChatItemGrouper } from './toolGroups' import AIChatInput from './AIChatInput.svelte' import { + READ_STARTER_PLACEHOLDER, STARTER_PLACEHOLDER, USE_STARTER_PLACEHOLDER, type ComposerSelection @@ -133,7 +136,8 @@ onAttachmentsChange = undefined, placeholder = undefined, scrollElement = $bindable(), - onTranscriptScroll = undefined + onTranscriptScroll = undefined, + stickyUserMessage = false }: { messages: DisplayMessage[] pastChats: { id: string; title: string }[] @@ -181,9 +185,13 @@ * needs it to measure and restore the scroll position. */ scrollElement?: HTMLDivElement | undefined onTranscriptScroll?: () => void + /** Pin a one-line copy of the user message whose turn is being read to the + * transcript's top, once the message itself has scrolled out above it. */ + stickyUserMessage?: boolean } = $props() let aiChatInput: AIChatInput | undefined = $state() + let composerFocused = $state(false) let assistantSettings: AssistantSettingsModal | undefined = $state() // The "+" menu's skill and MCP rows: enough state to check and flip one, with // everything else about them behind the assistant settings modal. @@ -194,6 +202,49 @@ const groupChatItems = createChatItemGrouper() const chatItems = $derived(groupChatItems(messages)) + // Mounting a message parses its markdown, so a long transcript mounted at once blocks the + // page for every message in it. Only the tail is mounted when a transcript arrives; older + // items mount in batches as the reader scrolls toward them, and stay mounted. + const TAIL_ITEMS = 30 + const REVEAL_BATCH = 30 + const REVEAL_MARGIN_PX = 600 + const transcriptKey = $derived(messages[0]?.content) + // How many items are hidden, counted from the item holding message `first`. + let revealed = $state<{ first: string | undefined; hidden: number }>() + const hiddenHead = $derived.by(() => { + const first = transcriptKey + const r = revealed + return untrack(() => { + if (r && r.first === first) return r.hidden + // The message it was counted from moved down: a host prepended a page of older + // messages (the flow chat does), which stays hidden unless everything above was shown. + const moved = r ? messages.findIndex((m) => m.content === r.first) : -1 + if (r && moved > 0) { + if (r.hidden === 0) return 0 + return r.hidden + chatItems.findIndex((item) => chatItemStart(item) >= moved) + } + // Another transcript: the reload of the same chat keeps its first message. + return Math.max(0, chatItems.length - TAIL_ITEMS) + }) + }) + // A swap the key misses (two chats opening with the same message) keeps the previous chat's + // count: clamped so that count can never hide the tail, though a low one mounts more than needed. + const shownFrom = $derived(Math.min(hiddenHead, Math.max(0, chatItems.length - TAIL_ITEMS))) + + function chatItemStart(item: (typeof chatItems)[number]): number { + return item.kind === 'group' ? (item.entries[0]?.index ?? 0) : item.index + } + + function revealOlder() { + if (!scrollElement || shownFrom === 0 || scrollElement.scrollTop >= REVEAL_MARGIN_PX) return + // Assigned from the distance to the bottom rather than added to, so it holds whether or + // not the browser's own scroll anchoring already moved the position. + const fromBottom = scrollElement.scrollHeight - scrollElement.scrollTop + revealed = { first: transcriptKey, hidden: Math.max(0, shownFrom - REVEAL_BATCH) } + flushSync() + scrollElement.scrollTop = scrollElement.scrollHeight - fromBottom + } + // Escape stops the generation when focus is on the chat (or parked on // body), but stays with other widgets (e.g. the session's Monaco editor). // Capture phase is required: Monaco and mounted-but-closed Modal2 @@ -242,8 +293,9 @@ // flow's tool rows have their own job, and a stopped turn can end on a tool row. // None in a turn still running, paused on the user included (their reply lands as a tool // result, so a row shown during the pause would vanish again): which answer ends the turn is - // unknown until it does, and one followed by a tool call would leave the row's blank gap above - // it. A manual compaction loads without a turn of its own, so the last turn keeps its row. + // unknown until it does, and the row draws into the gap below its answer, over a following + // tool call. A manual compaction loads without a turn of its own, so the last turn keeps its + // row. const showsAnswerActions = $derived.by(() => { const shows: boolean[] = new Array(messages.length).fill(false) const answeredLater = new Set<string | undefined>() @@ -266,11 +318,75 @@ sticker.scrollToEnd(scrollElement) } + // Each turn (a user message and what follows it, up to the next one) is its own box, so a + // sticky copy of its user message stays inside it and the next turn pushes it out. + // Turns are keyed over the whole transcript so the one cut by `shownFrom` keeps its key, and + // its box, as older items are revealed into it. + const turns = $derived.by(() => { + const out: { key: string; items: typeof chatItems }[] = [] + chatItems.forEach((item, i) => { + const startsTurn = item.kind === 'message' && item.message.role === 'user' + if (out.length === 0 || (stickyUserMessage && startsTurn)) { + out.push({ key: chatItemKey(item), items: [] }) + } + if (i >= shownFrom) out[out.length - 1].items.push(item) + }) + return out.filter((turn) => turn.items.length > 0) + }) + function userMessageText(message: DisplayMessage): string { + return segments(messageDraft(message)) + .map((seg) => (seg.type === 'text' ? seg.value : `Pasted ${lineCountLabel(seg.att.lines)}`)) + .join('') + } + // The sticky copy stays invisible until the real bubble reaches it: the copy sticks 16px + // earlier (the message's top margin), so at the hand-over both sit on the same pixels. + let pinnedUserIndex = $state(-1) + // The message's wrapper always follows its sticky copy (see `messageRow`). A message being + // edited has no bubble, so its own top stands in: its turn stays measured and keeps its copy. + function anchorOf(sticky: HTMLElement): Element | null | undefined { + const message = sticky.nextElementSibling + return message?.querySelector('[data-user-bubble]') ?? message?.firstElementChild + } + function measurePinnedUserMessage() { + if (!stickyUserMessage || !scrollElement) return + let pinned = -1 + const stickies = scrollElement.querySelectorAll<HTMLElement>('[data-sticky-user]') + const top = scrollElement.getBoundingClientRect().top + for (const sticky of Array.from(stickies)) { + const message = sticky.nextElementSibling + const bubble = message?.querySelector('[data-user-bubble]') + const anchor = bubble ?? message?.firstElementChild + if (!anchor) continue + const stickyRect = sticky.getBoundingClientRect() + // An editor's root can start level with the copy (the first message has no top + // margin), so it counts only once it has slid under it. + const under = bubble + ? anchor.getBoundingClientRect().top <= stickyRect.top + 0.5 + : anchor.getBoundingClientRect().top < stickyRect.top - 0.5 + if (!under) break + // A copy its turn has pushed out above the transcript pins nothing: a following turn + // without a copy of its own (attachments only) gets the normal top fade back. + pinned = stickyRect.bottom > top ? Number(sticky.dataset.stickyUser) : -1 + } + pinnedUserIndex = pinned + } + function scrollToUserMessage(event: MouseEvent) { + const sticky = (event.currentTarget as HTMLElement).closest<HTMLElement>('[data-sticky-user]') + const anchor = sticky && anchorOf(sticky) + if (!scrollElement || !sticky || !anchor) return + const offset = anchor.getBoundingClientRect().top - sticky.getBoundingClientRect().top - 16 + scrollElement.scrollBy({ top: offset, behavior: 'smooth' }) + } + let height = $state(0) $effect(() => { if (chatHost.automaticScroll && height) { scrollDown() } + // Content growing or shrinking moves the user messages without a scroll event. + if (height) { + measurePinnedUserMessage() + } // Recompute the scroll-to-latest visibility on every content-height // change. `onScroll` only fires for actual scroll events, so without // this the arrow can go stale when content grows past the threshold @@ -279,6 +395,9 @@ const distance = scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight showScrollToLatest = distance > SCROLL_TO_LATEST_THRESHOLD_PX + // A tail too short to scroll fires no scroll event, so nothing else would mount the rest. + // Untracked: a reveal re-running this effect would scroll a following reader back down. + if (untrack(() => shownFrom) > 0) requestAnimationFrame(revealOlder) } }) @@ -296,6 +415,7 @@ // whose only event would otherwise be swallowed, leaving the arrow // stuck visible after we already reached the bottom. showScrollToLatest = distance > SCROLL_TO_LATEST_THRESHOLD_PX + measurePinnedUserMessage() if (sticker.isOwnScroll()) { return } @@ -304,6 +424,9 @@ } else { chatHost.disableAutomaticScroll() } + // After follow mode is settled, so the reveal cannot scroll a reader leaving the end back + // down; before the host's own paging, which waits until nothing here is left to mount. + revealOlder() onTranscriptScroll?.() } @@ -342,8 +465,11 @@ // Also shown for a run held by another tab, labeled with where it is: the // dots say a turn is in flight even before the reader reaches the footer - // note. Remote runs pause nothing and offer no Stop — this tab can't cancel. - const showTypingIndicator = $derived(chatHost.loading || chatHost.runHeldElsewhere) + // note. Remote runs pause nothing and offer no Stop — this tab can't cancel. A turn + // that answered and waits on background work writes nothing, so it shows none. + const showTypingIndicator = $derived( + (chatHost.loading && !chatHost.backgroundWait) || chatHost.runHeldElsewhere + ) // The manual `@` context-picker button. Shown in SCRIPT/FLOW (workspace items + // code blocks) and APP (datatables, frontend files). Hidden in GLOBAL — there @@ -971,39 +1097,77 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> {/if} </p> {/if} - <AIChatMessage - {message} - {messageIndex} - {availableContext} - bind:editingMessageIndex - {isLast} - {inGroup} - showAnswerActions={showsAnswerActions[messageIndex]} - /> + {@const hasStickyCopy = + stickyUserMessage && message.role === 'user' && message.content.trim() !== ''} + {#if hasStickyCopy} + {@const pinned = pinnedUserIndex === messageIndex} + <!-- Keeps its full height (the bubble's one line) inside the turn, so the turn's + end pushes it out; the message below takes that height back with -mt-8. --> + <div + class="sticky top-0 z-10 h-8 px-2 bg-surface pointer-events-none" + class:invisible={!pinned} + data-sticky-user={messageIndex} + > + <!-- The transcript's top fade moves under the pinned row: a solid band up to + the scroller's edge above it, the gradient below it. --> + <div class="absolute inset-x-0 bottom-full h-4 bg-surface"></div> + <div + class="absolute inset-x-0 top-full h-4 bg-gradient-to-b from-surface to-transparent" + ></div> + <div class="w-fit max-w-[min(32rem,100%)] rounded-lg bg-surface"> + <button + type="button" + class="block w-full text-left text-xs font-normal px-3 py-2 bg-surface-accent-selected text-accent rounded-lg" + class:pointer-events-auto={pinned} + title="Scroll to this message" + onclick={scrollToUserMessage} + > + <span class="line-clamp-1 whitespace-pre-wrap break-words" + >{userMessageText(message)}</span + > + </button> + </div> + </div> + {/if} + <div class={twMerge('flex flex-col min-w-0', hasStickyCopy && '-mt-8')}> + <AIChatMessage + {message} + {messageIndex} + {availableContext} + bind:editingMessageIndex + {isLast} + {inGroup} + showAnswerActions={showsAnswerActions[messageIndex]} + /> + </div> {/snippet} {#snippet groupRow(message: DisplayMessage, messageIndex: number)} {@render messageRow(message, messageIndex, false, true)} {/snippet} - {#each chatItems as item (chatItemKey(item))} - {#if item.kind === 'group'} - <div - class={twMerge( - 'mb-1 min-w-0 text-sm px-2 text-primary', - item.entries.at(-1)?.index === messages.length - 1 && '!mb-12' - )} - > - <div class="px-[1px]"> - <ToolGroupDisplay group={item} entry={groupRow} /> - </div> - </div> - {:else} - {@render messageRow( - item.message, - item.index, - item.index === messages.length - 1, - false - )} - {/if} + {#each turns as turn (turn.key)} + <div class="flex flex-col min-w-0"> + {#each turn.items as item (chatItemKey(item))} + {#if item.kind === 'group'} + <div + class={twMerge( + 'mb-2 min-w-0 text-sm px-2 text-primary', + item.entries.at(-1)?.index === messages.length - 1 && '!mb-12' + )} + > + <div class="px-[1px]"> + <ToolGroupDisplay group={item} entry={groupRow} /> + </div> + </div> + {:else} + {@render messageRow( + item.message, + item.index, + item.index === messages.length - 1, + false + )} + {/if} + {/each} + </div> {/each} {#if freeTierExhausted} {@render freeTierExhaustedBanner()} @@ -1036,7 +1200,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> </div> </div> <!-- Sits below the scroll-to-latest button, which carries z-10. --> - <ScrollFade scroller={scrollElement} /> + <ScrollFade scroller={scrollElement} class={pinnedUserIndex >= 0 ? 'hidden' : ''} /> {#if showScrollToLatest} <div transition:fade={{ duration: 120 }} @@ -1140,7 +1304,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> </div> {/if} <div> - <QueuedMessageChip /> + <QueuedMessageChip {composerFocused} onFocusComposer={() => aiChatInput?.focusInput()} /> {#if chatHost.mode === AIMode.GLOBAL && !chatHost.isSessionChat} <!-- Standalone Jobs bar for the global side-panel chat. In /sessions the Jobs segment lives inside the session bar (SessionChangesBar). --> @@ -1164,9 +1328,11 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> bind:selectedContext {availableContext} placeholder={starterLayout - ? heldInUse - ? USE_STARTER_PLACEHOLDER - : STARTER_PLACEHOLDER + ? workModeLock?.readsOnly + ? READ_STARTER_PLACEHOLDER + : heldInUse + ? USE_STARTER_PLACEHOLDER + : STARTER_PLACEHOLDER : placeholder} {initialInstructions} {onDraftChange} @@ -1180,6 +1346,7 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> collapsed={composerCollapsed} chatIcon={starterLayout} {onSent} + onComposerFocusChange={(focused) => (composerFocused = focused)} clearHint={!starterLayout && clearHintShown} > {#snippet collapsedControls()} diff --git a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte index f3b49d680b..fa2d676590 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte @@ -44,7 +44,6 @@ type AttachedImage } from './imageUtils' import { modelSupportsVision } from '../modelConfig' - import { tryGetCurrentModel } from '$lib/aiStore' import { createLongHash } from '$lib/editorLangUtils' import { fileToAttachedTextFile, @@ -125,6 +124,8 @@ chatIcon?: boolean /** After a new turn is handed to the host — not an edit, a queued message or an answer. */ onSent?: () => void + /** The textarea gained or lost focus. */ + onComposerFocusChange?: (focused: boolean) => void /** The composer's controls. */ toolbar?: Snippet } @@ -155,6 +156,7 @@ onAttachmentsChange = undefined, pendingQuestionToolCallId = undefined, onSent = undefined, + onComposerFocusChange = undefined, toolbar = undefined, hero = false, collapsed = false, @@ -334,11 +336,9 @@ if (imageFiles.length === 0) return // The vision check is about the model this composer's own turn will hit, so it // only applies to a host that picks that model. Elsewhere the model is chosen - // in the flow and tryGetCurrentModel would answer for the wrong one. + // in the flow and the host's model would answer for the wrong one. if (chatHost.supportsModelSettings) { - // tryGetCurrentModel returns undefined instead of throwing: this runs from a - // drop/paste handler that can't surface a rejection. - const model = tryGetCurrentModel() + const model = chatHost.currentModel // Only known text-only models fail this, so attaching would certainly 400 the // next turn — refuse rather than warn and send it anyway. if (model && !modelSupportsVision(model.provider, model.model)) { @@ -887,6 +887,15 @@ // this node without being outside the composer. Dismissing on them would // discard the edit the user opened the image from. if (isImageViewerOpen()) return + // The pinned one-line copy of the message being edited (AIChatDisplay) brings the + // editor back into view; dismissing on it would discard the edit. + const target = event.target as Element | null + if ( + editingMessageIndex !== null && + target?.closest?.(`[data-sticky-user="${editingMessageIndex}"]`) + ) { + return + } if (node && !node.contains(event.target as Node)) { onClickOutside() } @@ -975,7 +984,9 @@ chatManager.contextManager?.consumeMentionContext() } - function sendRequest() { + /** `midTurn`: Ctrl/⌘+Enter, which sends a message queued behind a running turn into that + * turn instead of after it (`ChatViewHost.sendQueuedMidTurn`). */ + function sendRequest({ midTurn = false }: { midTurn?: boolean } = {}) { // The send button is disabled while decoding, but Enter reaches here directly. // Sending now would drop the in-flight attachments onto the following message. if (pendingImages > 0 || pendingFiles > 0 || pendingBlobs > 0 || ingestionHolds > 0) { @@ -1013,21 +1024,22 @@ // context-only draft counts too (mirrors the idle send guard), and // the selection is pinned to the queued entry so the flush sends the // chips picked at press time. - if ( - editingMessageIndex === null && - (!draft.isEmpty || (chatHost.mode === AIMode.GLOBAL && selectedContext.length > 0)) - ) { - const sent = draft.take() - chatHost.queueMessage( - expanded(chatDraft(sent.text, sent.pastes)), - sent.images, - [...selectedContext], - sent.files, - sent.blobs - ) - // Consumed at enqueue, not at flush: the entry above pinned them. - consumeMentionsIfGlobal() - contextTextareaComponent?.clearForSend() + if (editingMessageIndex === null) { + if (!draft.isEmpty || (chatHost.mode === AIMode.GLOBAL && selectedContext.length > 0)) { + const sent = draft.take() + chatHost.queueMessage( + expanded(chatDraft(sent.text, sent.pastes)), + sent.images, + [...selectedContext], + sent.files, + sent.blobs + ) + // Consumed at enqueue, not at flush: the entry above pinned them. + consumeMentionsIfGlobal() + contextTextareaComponent?.clearForSend() + } + // With an empty composer, this marks what is already queued. + if (midTurn && chatHost.supportsMidTurnMessages) chatHost.sendQueuedMidTurn() } return } @@ -1077,11 +1089,20 @@ // A custom `onSendRequest` consumer (e.g. the inline ⌘K widget) has no chip // display, so it gets the fully expanded text; the default path keeps tokens // for the conversation bubble and expands them for the LLM inside the manager. - function submitRequest() { + /** Enter in a plain textarea. Ctrl/⌘ sends without stopping, and that press stops here for + * the same reason as in `ContextTextarea`: pages bind their own Ctrl/⌘+Enter on the window. */ + function sendFromEnter(e: KeyboardEvent) { + e.preventDefault() + const midTurn = e.ctrlKey || e.metaKey + if (midTurn) e.stopPropagation() + sendRequest({ midTurn }) + } + + function submitRequest(options: { midTurn?: boolean } = {}) { if (onSendRequest) { onSendRequest(expanded(chatDraft(draft.text, draft.pastes))) } else { - sendRequest() + sendRequest(options) } } @@ -1466,6 +1487,12 @@ use:clickOutside class="relative mt-1" role="presentation" + onfocusin={(e) => { + if (e.target instanceof HTMLTextAreaElement) onComposerFocusChange?.(true) + }} + onfocusout={(e) => { + if (e.target instanceof HTMLTextAreaElement) onComposerFocusChange?.(false) + }} onkeydown={(e) => { if (e.key === 'Escape' && chatHost.loading) { e.preventDefault() @@ -1483,7 +1510,7 @@ ingestionHolds === 0 ) { // Shell-style recall: ArrowUp in the empty main composer pulls the - // queued message (if any, same as the queued-message chip's click/X) + // queued message (if any, same as the queued-message chip's X) // or otherwise a copy of the last sent message back into the input. // Empty means no attachment still decoding/reading either — // recalling over an attachments-only draft would clobber it. @@ -1533,11 +1560,11 @@ onRemoveContext={(element) => { selectedContext = selectedContext?.filter((c) => !isSameContextElement(c, element)) }} - onSendRequest={() => { + onSendRequest={({ withModifier }) => { if (disabled) { return } - submitRequest() + submitRequest({ midTurn: withModifier }) }} {disabled} {onKeyDown} @@ -1588,8 +1615,7 @@ return } if (e.key === 'Enter' && !e.shiftKey) { - e.preventDefault() - sendRequest() + sendFromEnter(e) } }} rows={1} @@ -1647,8 +1673,7 @@ // An Enter that confirms an IME composition (Japanese, Chinese) is not a // send; it would ship the unfinished text. if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { - e.preventDefault() - sendRequest() + sendFromEnter(e) } }} rows={1} diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts index 6c8142fa72..82c88ddbde 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -59,6 +59,7 @@ import { prepareNavigatorUserMessage } from './navigator/core' import { sendUserToast } from '$lib/toast' import { AI_PROVIDERS, workspaceAIClients, getStreamedCompletionText } from '../lib' import { logFeatureUsage } from '$lib/utils/featureUsage' +import { logDisplayBlocks } from '$lib/components/display/displayTelemetry' import { modelSupportsVision } from '../modelConfig' import { getEffectiveModelContextWindow } from '../modelConfig' import { @@ -98,7 +99,17 @@ import { fromStore, get } from 'svelte/store' import type { ProviderToolSummary } from './agentContext' import { BROWSER } from 'esm-env' import { roleCapabilities, workspaceStore, type DBSchemas } from '$lib/stores' -import { copilotInfo, copilotSessionModel } from '$lib/aiStore' +import { + copilotInfo, + copilotSessionModel, + getWorkspaceCopilotInfo, + loadWorkspaceCopilotInfo, + resolveModelFor, + tryResolveModelFor, + type AiTarget, + type CopilotInfo +} from '$lib/aiStore' +import type { ReasoningProviderModel } from '../reasoningRegistry' import { copilotWorkspaceRequested, loadCopilot } from '$lib/components/copilot/loadCopilot' import { askTools, prepareAskSystemMessage, prepareAskUserMessage } from './ask/core' import { readDocsPageTool, searchDocsTool } from './docs/core' @@ -143,6 +154,7 @@ import { resolveSessionAccess } from './global/sessionAccess' import { canBuild, isReadOnlyAccess, + NO_RUN_ACCESS, USE_MODE_ACCESS, type SessionAccess, type SessionTool @@ -265,6 +277,10 @@ const COMPACT_COMMAND_RE = /^\/compact\s*$/ // resets to a fresh chat (the "New chat" action), instead of sending a turn. const CLEAR_COMMAND_NAME = 'clear' const CLEAR_COMMAND_RE = /^\/clear\s*$/ +function isLocalCommand(text: string): boolean { + const trimmed = text.trim() + return COMPACT_COMMAND_RE.test(trimmed) || CLEAR_COMMAND_RE.test(trimmed) +} const AI_AUTONOMY_MODE_STORAGE_KEY = 'ai-chat-autonomy-mode' const LEGACY_AUTO_ACCEPT_TOOL_CONFIRMATIONS_STORAGE_KEY = 'ai-chat-yolo-mode' const WEB_SEARCH_ERROR_HINT = @@ -491,6 +507,8 @@ export class AIChatManager implements ChatViewHost { // affordances apply here. See ChatViewHost for hosts where they don't. supportsModelSettings = true supportsMessageEditing = true + readonly stopSendsQueuedMessage = true + readonly supportsMidTurnMessages = true // The copilot turn is the attachments themselves when there is no text. requiresMessageText = false // Attachments and linked folders are GLOBAL-mode affordances. Declared as @@ -543,6 +561,33 @@ export class AIChatManager implements ChatViewHost { // what was selected at queue time (e.g. an inline element prompt submitted mid- // stream) rather than the live selection, which may change before the flush. queuedContext = $state<ContextElement[] | undefined>(undefined) + // The turn `sendQueuedMidTurn` marked the queue for, by its abort controller: a turn + // that ends without taking the queue (an error, a failed compaction) leaves it + // queued, and the mark must not carry it into the next turn. + #queueSendsMidTurnIn = $state<AbortController | undefined>(undefined) + get queuedSendsMidTurn(): boolean { + return ( + this.loading && + this.#queueSendsMidTurnIn !== undefined && + this.#queueSendsMidTurnIn === this.abortController && + !this.#queueWaitsForTurnEnd() + ) + } + /** A queue the turn-start send would refuse or trim: it goes out with that send, after + * the turn. `/compact` and `/clear` act on the whole conversation. Read live, since the + * queue and the session's model can change after the mark. */ + #queueWaitsForTurnEnd(): boolean { + if (isLocalCommand(this.queuedMessage)) return true + if ( + (this.queuedImages.length > 0 || this.queuedFiles.length > 0) && + this.mode !== AIMode.GLOBAL + ) + return true + const model = this.currentModel + return ( + this.queuedImages.length > 0 && !!model && !modelSupportsVision(model.provider, model.model) + ) + } get queuedMessage(): string { return this.#queuedDraft.text } @@ -564,6 +609,18 @@ export class AIChatManager implements ChatViewHost { // when the chat is idle, an auto-resume turn started for them (see // #maybeAutoResumeFromJobs). Ephemeral like queuedMessage — not persisted. pendingJobNotes = $state<string[]>([]) + // Notes about something that happened outside a turn, delivered with the job notes. + // Persisted on the chat record, unlike the job notes, because nothing re-derives + // them after a reload. + #modelNotes: string[] = [] + /** Tell the model about something that happened outside a turn, on its next turn. */ + async queueModelNote(note: string) { + this.#modelNotes = [...this.#modelNotes, note] + await this.historyManager.setModelNotes( + this.historyManager.getCurrentChatId(), + this.#modelNotes + ) + } // Guards #maybeAutoResumeFromJobs against re-entering while its own turn spins up. #autoResuming = false #jobPollTimer: ReturnType<typeof setTimeout> | undefined = undefined @@ -707,8 +764,11 @@ export class AIChatManager implements ChatViewHost { if (this.reasoningSummaryUnavailableFor.length === 0) { return undefined } - const provider = getCurrentModel().provider - if (!this.reasoningSummaryUnavailableFor.includes(this.reasoningSummaryKey(provider))) { + const provider = this.currentModel?.provider + if ( + !provider || + !this.reasoningSummaryUnavailableFor.includes(this.reasoningSummaryKey(provider)) + ) { return undefined } return `Thinking (hidden, ${providerDisplayName(provider)} org not verified)` @@ -775,6 +835,12 @@ export class AIChatManager implements ChatViewHost { /** Use, Plan or Build. A session keeps its own: the runtime seeds it from the session record * and stores each change through `onWorkModeChanged`. */ workMode = $state<AIWorkMode>(AIWorkMode.BUILD) + /** The session is moving into a fork. Its editors stay closed meanwhile: an edit would save a + * draft in the workspace being left, after the move listed what it brings along. */ + moving = $state(false) + /** A move into a fork has started: no turn starts until it ends, retries and edits included. + * Set before `moving`, which waits for the editors to hand over their pending edits. */ + moveStarted = $state(false) onWorkModeChanged: ((mode: AIWorkMode) => void) | undefined = undefined workModesAvailable = $derived(this.isSessionChat && supportsPlanMode(this.mode)) /** Use is the only mode: the workspace is protected, or the user's role builds nothing in it. */ @@ -795,8 +861,9 @@ export class AIChatManager implements ChatViewHost { ) /** Why the chat is in Use; undefined in Plan and Build. A protected workspace's access builds * nothing too, so it is told apart from the role first. */ - #useReason = $derived.by((): 'protected' | 'role' | 'chosen' | undefined => { + #useReason = $derived.by((): 'protected' | 'view_only' | 'role' | 'chosen' | undefined => { if (!this.useModeActive) return undefined + if (this.sessionAccess && !this.sessionAccess.has('run')) return 'view_only' if (isReadOnlyAccess(this.sessionAccess)) return 'protected' return this.#useOnly ? 'role' : 'chosen' }) @@ -813,7 +880,13 @@ export class AIChatManager implements ChatViewHost { return this.useModeActive || this.planModeActive ? undefined : ENTER_USE_MODE_TOOL }) /** What the tools and the prompt are built for. */ - #toolAccess = $derived(this.useModeActive ? USE_MODE_ACCESS : this.sessionAccess) + #toolAccess = $derived( + !this.useModeActive + ? this.sessionAccess + : this.#useReason === 'view_only' + ? NO_RUN_ACCESS + : USE_MODE_ACCESS + ) // The posture's own state — its two tools, the plan document and the planning round. // Everything it needs from this manager goes through the host above. planMode = new PlanModeController(planModeHostFor(this)) @@ -860,16 +933,12 @@ export class AIChatManager implements ChatViewHost { #copilotInfo = fromStore(copilotInfo) #sessionModel = fromStore(copilotSessionModel) /** Capabilities the provider runs on its own servers, attached by the adapter at send - * time. Never part of `tools`: the request path would try to dispatch them. The two - * `void` reads only subscribe: the model helpers read through `get()`, which tracks - * nothing, so a change of model or of the workspace's AI config would otherwise not - * re-derive. A workspace switch re-derives through the AI config it loads. */ + * time. Never part of `tools`: the request path would try to dispatch them. */ get providerTools(): ProviderToolSummary[] { - void this.#copilotInfo.current - void this.#sessionModel.current - const model = tryGetCurrentModel() - if (!model || (model.provider === 'openai' && this.skipResponsesApi)) return [] - const enabled = isWebSearchEnabledForProvider(model.provider) + const model = this.currentModel + const info = this.aiInfo + if (!model || !info || (model.provider === 'openai' && this.skipResponsesApi)) return [] + const enabled = isWebSearchEnabledForProvider(model.provider, info) return sendsWebSearch(this.operatingWorkspace ?? '', model, enabled) ? [ { @@ -1061,6 +1130,37 @@ export class AIChatManager implements ChatViewHost { return this.workspaceResolver?.() ?? get(workspaceStore) } + /** The AI config this chat sends with. A session's is its own workspace's, never the tab's, + * which belongs to whatever workspace is on screen; other chats use the tab's. Undefined while + * a session's is still loading, and reading it starts the load. */ + get aiInfo(): CopilotInfo | undefined { + if (!this.isSessionChat) return this.#copilotInfo.current + const workspace = this.operatingWorkspace + return workspace ? getWorkspaceCopilotInfo(workspace) : undefined + } + + /** The session's workspace and loaded config, for code that cannot wait for the load. */ + get loadedSessionAiTarget(): AiTarget | undefined { + const info = this.isSessionChat ? this.aiInfo : undefined + const workspace = this.operatingWorkspace + return info && workspace ? { workspace, info } : undefined + } + + get currentModel(): ReasoningProviderModel | undefined { + // Subscribes only: the model helpers read through `get()`, which tracks nothing. + void this.#sessionModel.current + const info = this.aiInfo + return info && tryResolveModelFor(info) + } + + /** Resolved at each request, after any fork commit. Undefined for other chats, whose requests + * use the tab's. */ + sessionAiTarget = async (): Promise<AiTarget | undefined> => { + if (!this.isSessionChat) return undefined + const workspace = this.operatingWorkspace ?? '' + return { workspace, info: await loadWorkspaceCopilotInfo(workspace) } + } + // Fired whenever the active chat id changes away from the one the consumer // knows (a "/clear" rotation or a history switch). Session runtimes wire this // to keep the session record's chatId aligned — the compare-page handoff @@ -1325,6 +1425,7 @@ export class AIChatManager implements ChatViewHost { if (pending.length === 0) return let anyTerminal = false + let anyStreaming = false for (const job of pending) { try { // Its own output first, so a run that detached out of the inline wait keeps @@ -1337,6 +1438,7 @@ export class AIChatManager implements ChatViewHost { } const update = await reader.poll() if (gen !== this.#jobPollGeneration) return + if (update?.streamed && !update.completed) anyStreaming = true // Only what this reader has collected: the patch is spread over the card, so // naming a field it has nothing for erases output already on it. if (update?.logs || update?.resultStream) { @@ -1429,9 +1531,11 @@ export class AIChatManager implements ChatViewHost { void this.#persistBackgroundJobs() } - // Reschedule while anything is still in flight, backing off up to 5s. + // Reschedule while anything is still in flight, backing off up to 5s — except after a + // poll that brought new stream output: the card shows the partial as it arrives, and + // at 5s that reads as a freeze then a jump of a thousand characters. if (this.backgroundJobs.some((j) => j.detached && this.isJobNonTerminal(j.status))) { - this.#jobPollDelay = Math.min(this.#jobPollDelay + 1000, 5000) + this.#jobPollDelay = anyStreaming ? 1000 : Math.min(this.#jobPollDelay + 1000, 5000) this.#scheduleJobPoll() } @@ -1500,8 +1604,21 @@ export class AIChatManager implements ChatViewHost { }, 5_000) } + #autoResumeHolds = 0 + /** Keep background-job completions from starting a turn until the returned release runs. */ + holdAutoResume(): () => void { + this.#autoResumeHolds++ + let released = false + return () => { + if (released) return + released = true + this.#autoResumeHolds-- + void this.#maybeAutoResumeFromJobs() + } + } + async #maybeAutoResumeFromJobs() { - if (this.#autoResuming) return + if (this.#autoResuming || this.#autoResumeHolds > 0) return // Global/sessions chat only (the only mode with a jobs tray + preamble). if (this.mode !== AIMode.GLOBAL) return // Mid-turn: the notes will ride that turn's preamble, so don't start another. @@ -1559,6 +1676,7 @@ export class AIChatManager implements ChatViewHost { this.#jobUpdateReaders.clear() this.backgroundJobs = [] this.pendingJobNotes = [] + this.#modelNotes = [] } /** Merge a status patch into the tool card identified by tool_call_id, or @@ -1792,6 +1910,7 @@ export class AIChatManager implements ChatViewHost { ): Promise<'ok' | 'empty' | 'aborted' | 'error'> => { this.compacting = true try { + const target = await this.sessionAiTarget() // Cap the summarizer's output at the budget already reserved for the // summary: without a cap the model's default max_tokens applies. const raw = await getStreamedCompletionText( @@ -1802,7 +1921,7 @@ export class AIChatManager implements ChatViewHost { { role: 'user', content: getCompactionSummaryPrompt() } ], abortController, - { maxTokensCap: SUMMARY_OUTPUT_RESERVE_TOKENS } + { maxTokensCap: SUMMARY_OUTPUT_RESERVE_TOKENS, ...target } ) const formatted = formatCompactSummary(raw) if (!formatted) { @@ -1991,12 +2110,9 @@ export class AIChatManager implements ChatViewHost { model: ChatLoopConfig['modelProvider'] | undefined, inFlightTokens = 0 ): Promise<boolean> => { + const info = (await this.sessionAiTarget())?.info ?? get(copilotInfo) const contextWindow = model - ? getEffectiveModelContextWindow( - model.provider, - model.model, - get(copilotInfo).contextWindowPerModel - ) + ? getEffectiveModelContextWindow(model.provider, model.model, info.contextWindowPerModel) : undefined if (contextWindow === undefined || projectedTokens < contextWindow * COMPACTION_TRIGGER_RATIO) { return false @@ -2593,12 +2709,22 @@ export class AIChatManager implements ChatViewHost { context: this.queuedContext } this.queuedContext = undefined + this.#queueSendsMidTurnIn = undefined return taken } #clearQueue() { this.#queuedDraft.clear() this.queuedContext = undefined + this.#queueSendsMidTurnIn = undefined + } + + /** Ctrl+Enter while a turn runs: the queued message goes into that turn as soon as its + * running tool calls finish (`#takeMidTurnMessage`), instead of after the turn. */ + sendQueuedMidTurn() { + if (!this.loading || !this.#hasQueuedMessage()) return + if (this.#queueWaitsForTurnEnd()) return + this.#queueSendsMidTurnIn = this.abortController } /** Put a taken queue back after an auto-send bailed before becoming a turn. @@ -2893,6 +3019,7 @@ export class AIChatManager implements ChatViewHost { ? { sessionId: this.sessionId, operatingWorkspace: this.operatingWorkspace, + sessionAi: () => ({ model: this.currentModel, info: this.aiInfo }), artifacts: this.artifacts, access: this.#toolAccess, getChatId: () => this.historyManager.getCurrentChatId(), @@ -2923,7 +3050,10 @@ export class AIChatManager implements ChatViewHost { ensurePipeline: this.#ensurePipeline } : baseHelpers - this.systemMessage = assembleGlobalSystemMessage(getCustomPromptParts(AIMode.GLOBAL), opts) + this.systemMessage = assembleGlobalSystemMessage( + getCustomPromptParts(AIMode.GLOBAL, this.aiInfo?.customPrompts ?? {}), + opts + ) this.syncArtifactsSession() } @@ -3103,7 +3233,7 @@ export class AIChatManager implements ChatViewHost { return } this.systemMessage = assembleGlobalSystemMessage( - getCustomPromptParts(AIMode.GLOBAL), + getCustomPromptParts(AIMode.GLOBAL, this.aiInfo?.customPrompts ?? {}), this.globalAssemblyOpts() ) } @@ -3435,7 +3565,8 @@ export class AIChatManager implements ChatViewHost { } private notifyReasoningSummaryUnavailable = () => { - const provider = getCurrentModel().provider + const provider = this.currentModel?.provider + if (!provider) return const key = this.reasoningSummaryKey(provider) if (!this.reasoningSummaryUnavailableFor.includes(key)) { this.reasoningSummaryUnavailableFor = [...this.reasoningSummaryUnavailableFor, key] @@ -3453,7 +3584,8 @@ export class AIChatManager implements ChatViewHost { addedMessages, systemMessage: systemMessageOverride, onWebSearchUnavailable, - onBeforeIteration + onBeforeIteration, + takeMidTurnMessage }: { messages: ChatCompletionMessageParam[] abortController: AbortController @@ -3466,6 +3598,7 @@ export class AIChatManager implements ChatViewHost { systemMessage?: ChatCompletionSystemMessageParam onWebSearchUnavailable?: () => void onBeforeIteration?: ChatLoopConfig['onBeforeIteration'] + takeMidTurnMessage?: ChatLoopConfig['takeMidTurnMessage'] }) => { // Fresh batch for this turn — drop any images an aborted prior turn left buffered. this.pendingToolImages.clear() @@ -3482,9 +3615,12 @@ export class AIChatManager implements ChatViewHost { // while a response streams would bill it to the workspace the user landed // on rather than the one whose credentials and proxy served it. const usageWorkspace = this.operatingWorkspace + const target = await this.sessionAiTarget() + const info = target?.info const result = await runChatLoop({ messages, addedMessages, + takeMidTurnMessage, get systemMessage() { let base = systemMessageOverride ?? self.systemMessage // Inject the attached-files roster at request time (re-read each iteration) @@ -3502,7 +3638,7 @@ export class AIChatManager implements ChatViewHost { get tools() { return withWebSearchFallback( self.tools, - !!get(copilotInfo).webSearchBackend, + !!(info ?? get(copilotInfo)).webSearchBackend, self.providerTools.length > 0 ) }, @@ -3512,10 +3648,10 @@ export class AIChatManager implements ChatViewHost { abortController, callbacks, get modelProvider() { - return getCurrentModel() + return info ? resolveModelFor(info) : getCurrentModel() }, get webSearch() { - return isWebSearchEnabledForProvider(getCurrentModel().provider) + return isWebSearchEnabledForProvider(this.modelProvider.provider, info) }, // Build the proxy clients against the operating workspace, not the global // singleton: a session deliberately leaves workspaceStore untouched, so the @@ -3523,13 +3659,14 @@ export class AIChatManager implements ChatViewHost { // request through the navigation workspace's /ai/proxy instead of the // session's — sending it to the wrong workspace's AI credentials. get clients() { - const ws = self.operatingWorkspace ?? '' + const ws = target?.workspace ?? self.operatingWorkspace ?? '' return { openai: workspaceAIClients.createOpenaiClient(ws), anthropic: workspaceAIClients.createAnthropicClient(ws) } }, - workspace: this.operatingWorkspace ?? '', + workspace: target?.workspace ?? this.operatingWorkspace ?? '', + info, skipResponsesApi: this.skipResponsesApi, onSkipResponsesApi: () => { this.skipResponsesApi = true @@ -3724,6 +3861,125 @@ export class AIChatManager implements ChatViewHost { return this.#sendsAwaitingReady > 0 } + /** The message the model gets for `text`, framed for the current mode. Message-attached + * files travel as references: the prompt lists them by id and the model reads them with + * the file tools, so they are registered before the request goes out. A failed + * registration must not block the send — the reference reads as missing instead. */ + #buildUserMessage( + text: string, + context: ContextElement[], + images: AttachedImage[], + files: AttachedTextFile[] + ): ChatCompletionMessageParam { + if (this.mode === AIMode.GLOBAL && files.length > 0) { + try { + this.attachedFiles.registerMessageFiles(files as (AttachedTextFile & { id: string })[]) + } catch (e) { + console.error('Failed to register message-attached files', e) + } + } + switch (this.mode) { + case AIMode.FLOW: + return prepareFlowUserMessage( + text, + this.flowAiChatHelpers!.getFlowAndSelectedId(), + context, + this.flowAiChatHelpers!.inlineScriptSession, + { flowInputsLocked: !this.flowAiChatHelpers!.canEditFlowInputs() } + ) + case AIMode.NAVIGATOR: + return prepareNavigatorUserMessage(text) + case AIMode.ASK: + return prepareAskUserMessage(text) + case AIMode.SCRIPT: + return prepareScriptUserMessage(text, context) + case AIMode.API: + return prepareApiUserMessage(text) + case AIMode.GLOBAL: + return prepareGlobalUserMessage(text, context, { + workspace: this.operatingWorkspace, + activePreview: this.activePreviewResolver?.(), + activeEditor: this.activeEditorResolver?.(), + images, + files, + resourceTypeSync: this.resourceTypeSync + }) + case AIMode.APP: + return prepareAppUserMessage(text, this.appAiChatHelpers?.getSelectedContext(), context) + } + } + + /** The user rejected a tool call of the latest step. A user message read after a rejection + * makes the model retry the rejected call whatever the framing or the tool result say, so + * the queue waits: the model answers the rejection alone and the queue goes after the turn. */ + #lastStepDeclined(collectedMessages: ChatCompletionMessageParam[]): boolean { + const step = collectedMessages.findLast((m) => m.role === 'assistant' && m.tool_calls?.length) + if (step?.role !== 'assistant' || !step.tool_calls) return false + const ids = new Set(step.tool_calls.map((c) => c.id)) + return this.displayMessages.some( + (m) => m.role === 'tool' && ids.has(m.tool_call_id) && m.declinedByUser === true + ) + } + + /** The queued message as the next message of the running turn, once `sendQueuedMidTurn` + * marked it. Taken only after the turn has output that a stop keeps (`hasUsableOutput` + * in `sendRequestImpl`): a turn rolled back as unsent would drop the message with it. */ + #takeMidTurnMessage( + collectedMessages: ChatCompletionMessageParam[] + ): ChatCompletionMessageParam | undefined { + if (!this.queuedSendsMidTurn || !this.#hasQueuedMessage()) return undefined + if (this.abortController?.signal.aborted) return undefined + if (truncateToToolPairedPrefix(collectedMessages).length === 0) return undefined + if (this.#lastStepDeclined(collectedMessages)) { + // Unmarked, so the chip stops promising a mid-turn send. + this.#queueSendsMidTurnIn = undefined + return undefined + } + + const { draft, context = [] } = this.#takeQueue() + // Pinned at enqueue, so consumed from the live selection as any pinned send does. + for (const c of context) { + if (c.type === 'app_dom_selector') { + this.contextManager?.removeSelectedDomElement(c.selector, c.appPath) + } + } + if (this.mode === AIMode.SCRIPT || this.mode === AIMode.FLOW) { + this.contextManager?.updateContextOnRequest({}) + } + const files = withAttachedTextFileIds(draft.files) + const text = + draft.text.trim() || draft.images.length > 0 ? draft.text : '(the user sent an empty message)' + // Unframed, models read the message as a new request and drop the task in progress. + const message = this.#buildUserMessage( + `The user sent this message while you were working:\n${this.expandGlobalSkillCommand(text)}\n\nAddress it as you continue the task in progress. It may add to, change or cancel that task: do what it asks.`, + context, + draft.images, + files + ) + this.displayMessages = [ + ...this.displayMessages, + { + role: 'user', + content: draft.text, + images: draft.images.length > 0 ? draft.images : undefined, + files: files.length > 0 ? files : undefined, + contextElements: + this.mode === AIMode.SCRIPT || this.mode === AIMode.FLOW || this.mode === AIMode.GLOBAL + ? context + : undefined, + // The loop appends the message to the turn, which the turn's end appends to + // the stored history. + index: this.messages.length + collectedMessages.length + } + ] + logFeatureUsage('ai_chat', 'send_without_stopping', { + key: this.mode, + entityId: this.historyManager.getCurrentChatId(), + workspace: this.operatingWorkspace + }) + return message + } + sendRequest = async (options: Parameters<typeof this.sendRequestImpl>[0] = {}) => { if (this.#ready) { this.#sendsAwaitingReady++ @@ -3756,7 +4012,9 @@ export class AIChatManager implements ChatViewHost { // false`), and a copy here would double it. Paste tokens are expanded // into the text, as the queue does, because the restore lanes carry no // pastes. - if (this.runHeldElsewhere) { + // A move into a fork holds turns the same way: one started now would act on the + // workspace being left. The composer is locked then, but a retry or an edit is not. + if (this.runHeldElsewhere || this.moveStarted) { if (options.synthetic) { // Client-authored prompt (a job auto-resume), not user input: nothing // to hand back and no toast. Releasing the staged text un-blocks the @@ -3774,7 +4032,12 @@ export class AIChatManager implements ChatViewHost { options.files ) } - sendUserToast('This session is running in another tab. Your message was kept.', true) + sendUserToast( + this.moveStarted + ? 'This session is moving to another workspace. Your message was kept.' + : 'This session is running in another tab. Your message was kept.', + true + ) } return false } @@ -3973,7 +4236,7 @@ export class AIChatManager implements ChatViewHost { // only edit/retry of a pre-id transcript can arrive without one, and the // hash is deterministic, so hydration reproduces the original id. const files = withAttachedTextFileIds(options.files ?? []) - const sendModel = tryGetCurrentModel() + const sendModel = this.currentModel const modelIsBlind = !!sendModel && !modelSupportsVision(sendModel.provider, sendModel.model) if (requestedImages.length > 0 && modelIsBlind) { // An image-only message has nothing left once the images are dropped — @@ -4111,8 +4374,13 @@ export class AIChatManager implements ChatViewHost { this.refreshSessionAccess(this.operatingWorkspace ?? ''), resolveResourceTypeSync(this.operatingWorkspace ?? '', this.messages).then((sync) => { this.resourceTypeSync = sync - }) + }), + // Its workspace prompt goes into the system prompt rebuilt below. + this.sessionAiTarget().catch(() => {}) ]) + if (this.isSessionChat) { + this.rebuildGlobalSystemMessage() + } } // Stop/Escape during the beforeSend pre-flight aborted this send before any // request went out. Mirror the main "cancelled before usable output" recovery: @@ -4268,7 +4536,7 @@ export class AIChatManager implements ChatViewHost { // loading + abortController were set optimistically before beforeSend, above. this.#automaticScroll = true - const model = tryGetCurrentModel() + const model = this.currentModel if (model) { const chatId = this.historyManager.getCurrentChatId() logFeatureUsage('ai_chat', 'message', { @@ -4360,11 +4628,18 @@ export class AIChatManager implements ChatViewHost { // turn (notify-only wake). Folded into the model-facing text only — the // display bubble keeps this.instructions, and no extra message is added, so // the display↔messages index pairing above stays intact. Ephemeral. + const notes = [...this.#modelNotes, ...this.pendingJobNotes] const jobNotesPreamble = - this.mode === AIMode.GLOBAL && this.pendingJobNotes.length > 0 - ? this.pendingJobNotes.join('\n\n') + '\n\n' - : '' - if (jobNotesPreamble) this.pendingJobNotes = [] + this.mode === AIMode.GLOBAL && notes.length > 0 ? notes.join('\n\n') + '\n\n' : '' + if (jobNotesPreamble) { + this.pendingJobNotes = [] + if (this.#modelNotes.length > 0) { + this.#modelNotes = [] + void this.historyManager + .setModelNotes(this.historyManager.getCurrentChatId(), []) + .catch((e) => console.error('Failed to clear model notes', e)) + } + } const modelInstructions = this.mode === AIMode.GLOBAL ? jobNotesPreamble + this.expandGlobalSkillCommand(oldInstructions) @@ -4375,63 +4650,12 @@ export class AIChatManager implements ChatViewHost { throw new Error('No script options passed') } - // Message-attached files travel as references: the prompt lists them by id - // and the model reads their content via the file tools. Register them in - // the store before the request goes out so this turn's reads can already - // see them. Registration failure must not block the send — the reference - // just reads as missing and the model reports it. - if (this.mode === AIMode.GLOBAL && files.length > 0) { - try { - this.attachedFiles.registerMessageFiles(files as (AttachedTextFile & { id: string })[]) - } catch (e) { - console.error('Failed to register message-attached files', e) - } - } - - let userMessage: ChatCompletionMessageParam = { - role: 'user', - content: '' - } - switch (this.mode) { - case AIMode.FLOW: - userMessage = prepareFlowUserMessage( - oldInstructions, - this.flowAiChatHelpers!.getFlowAndSelectedId(), - oldSelectedContext, - this.flowAiChatHelpers!.inlineScriptSession, - { flowInputsLocked: !this.flowAiChatHelpers!.canEditFlowInputs() } - ) - break - case AIMode.NAVIGATOR: - userMessage = prepareNavigatorUserMessage(oldInstructions) - break - case AIMode.ASK: - userMessage = prepareAskUserMessage(oldInstructions) - break - case AIMode.SCRIPT: - userMessage = prepareScriptUserMessage(oldInstructions, oldSelectedContext) - break - case AIMode.API: - userMessage = prepareApiUserMessage(oldInstructions) - break - case AIMode.GLOBAL: - userMessage = prepareGlobalUserMessage(modelInstructions, oldSelectedContext, { - workspace: this.operatingWorkspace, - activePreview: this.activePreviewResolver?.(), - activeEditor: this.activeEditorResolver?.(), - images: sentImages, - files: files, - resourceTypeSync: this.resourceTypeSync - }) - break - case AIMode.APP: - userMessage = prepareAppUserMessage( - oldInstructions, - this.appAiChatHelpers?.getSelectedContext(), - oldSelectedContext - ) - break - } + const userMessage = this.#buildUserMessage( + modelInstructions, + oldSelectedContext, + sentImages, + files + ) // Size of the request about to go out: contextTokens (provider report // when current, fresh chars/4 estimate otherwise) plus the message @@ -4520,6 +4744,7 @@ export class AIChatManager implements ChatViewHost { // deduped in commitInterruptedTurn. if (this.currentReply) { partialReply = this.currentReply + logDisplayBlocks(this.currentReply) } if (this.currentReply || this.currentReasoning) { this.displayMessages = [ @@ -4606,6 +4831,7 @@ export class AIChatManager implements ChatViewHost { const result = await this.chatRequest({ ...params, addedMessages: collectedMessages, + takeMidTurnMessage: () => this.#takeMidTurnMessage(collectedMessages), onWebSearchUnavailable: () => { webSearchUnavailable = true }, @@ -4792,15 +5018,11 @@ export class AIChatManager implements ChatViewHost { if ( requestCarriedImages && messagesHaveImageParts(this.messages) && - isImageRejection(err, [ - sendModel?.model, - tryGetCurrentModel()?.model, - failingModel?.model - ]) + isImageRejection(err, [sendModel?.model, this.currentModel?.model, failingModel?.model]) ) { this.messages = stripImagePartsFromMessages(this.messages) sendUserToast( - `${tryGetCurrentModel()?.model ?? 'The model'} could not read the attached image(s), so they were removed from the conversation. Your message was kept.`, + `${this.currentModel?.model ?? 'The model'} could not read the attached image(s), so they were removed from the conversation. Your message was kept.`, true ) } @@ -4961,7 +5183,7 @@ export class AIChatManager implements ChatViewHost { // nothing yet, so there is nothing to restore. Un-submitted context-chip // edits are the one loss — the chips re-seed from the untouched message // on the next edit. - if (this.runHeldElsewhere) { + if (this.runHeldElsewhere || this.moveStarted) { if (newContent !== undefined) { this.restoreToInput( expanded(chatDraft(newContent, pastes ?? [])), @@ -4970,7 +5192,12 @@ export class AIChatManager implements ChatViewHost { ) } // "Text", not "message": chip edits are the part that does not survive. - sendUserToast('This session is running in another tab. Your text was kept.', true) + sendUserToast( + this.moveStarted + ? 'This session is moving to another workspace. Your text was kept.' + : 'This session is running in another tab. Your text was kept.', + true + ) return } @@ -5124,6 +5351,7 @@ export class AIChatManager implements ChatViewHost { if (this.isJobNonTerminal(j.status)) j.detached = true } if (this.backgroundJobs.length > 0) this.backgroundJobs = [...this.backgroundJobs] + this.#modelNotes = chat.modelNotes ?? [] // Reloading resolves no card on its own. Settle every one the poller above // will not reach, whoever wrote it — a record from a build that stored cards // without their jobs would otherwise restore one that spins forever. diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts index 9f6179a538..725e498e30 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts @@ -141,6 +141,11 @@ vi.mock('$lib/aiStore', () => ({ copilotSessionModel: writable(undefined), getCurrentModel: mocks.getCurrentModel, tryGetCurrentModel: mocks.tryGetCurrentModel, + // A session reads its own workspace's config; here every workspace has the same one. + getWorkspaceCopilotInfo: () => ({ enabled: true, workspaceDisabled: false, aiModels: [] }), + loadWorkspaceCopilotInfo: async () => ({ enabled: true, workspaceDisabled: false, aiModels: [] }), + resolveModelFor: mocks.getCurrentModel, + tryResolveModelFor: mocks.tryGetCurrentModel, getCombinedCustomPrompt: () => '', getCustomPromptParts: () => ({}), getUserCustomPrompts: () => ({}), @@ -1266,6 +1271,106 @@ describe('AIChatManager queued messages', () => { expect(input.prependText).toHaveBeenCalledWith('line one\nline two', [], []) }) + // Taken into the running turn, the message must not go out again as the next turn, and + // its bubble must point at its place in the stored history (editing it rewinds there). + it('sends a message marked to go without stopping into the running turn, once', async () => { + let taken: unknown + mocks.runChatLoop.mockImplementation(async (config: any) => { + manager.queueMessage('use Postgres instead') + manager.sendQueuedMidTurn() + config.addedMessages.push( + { + role: 'assistant', + content: '', + tool_calls: [{ id: 'call_1', type: 'function', function: { name: 'x', arguments: '{}' } }] + }, + { role: 'tool', tool_call_id: 'call_1', content: 'ok' } + ) + taken = config.takeMidTurnMessage() + config.addedMessages.push(taken, { role: 'assistant', content: 'done' }) + return { + addedMessages: config.addedMessages, + tokenUsage: { prompt: 0, completion: 0, total: 0 }, + hitMaxIterations: false + } + }) + const manager = createManager(createInputMock()) + + await manager.sendRequest({ instructions: 'build it' }) + + expect(mocks.runChatLoop).toHaveBeenCalledTimes(1) + expect(manager.queuedMessage).toBe('') + expect(JSON.stringify(taken)).toContain('use Postgres instead') + const bubble = manager.displayMessages.find( + (m) => m.role === 'user' && m.content === 'use Postgres instead' + ) as { index: number } | undefined + expect(manager.messages[bubble!.index]).toEqual(taken) + }) + + // A failed turn keeps the queue; its mark must not carry the message into the next turn. + it('drops the mark of a turn that fails, keeping the message queued', async () => { + const manager = createManager(createInputMock()) + mocks.runChatLoop.mockImplementationOnce(async () => { + manager.queueMessage('use Postgres instead') + manager.sendQueuedMidTurn() + throw new Error('provider down') + }) + let taken: unknown = 'not called' + mocks.runChatLoop.mockImplementationOnce(async (config: any) => { + config.addedMessages.push( + { + role: 'assistant', + content: '', + tool_calls: [{ id: 'call_1', type: 'function', function: { name: 'x', arguments: '{}' } }] + }, + { role: 'tool', tool_call_id: 'call_1', content: 'ok' } + ) + taken = config.takeMidTurnMessage() + throw new Error('provider down') + }) + + await manager.sendRequest({ instructions: 'build it' }) + expect(manager.queuedMessage).toBe('use Postgres instead') + expect(manager.queuedSendsMidTurn).toBe(false) + + await manager.sendRequest({ instructions: 'try again' }) + expect(taken).toBeUndefined() + expect(manager.queuedMessage).toBe('use Postgres instead') + }) + + it('holds a marked message after the user rejects a tool call, sending it after the turn', async () => { + const manager = createManager(createInputMock()) + let taken: unknown = 'not called' + let markedAfter: boolean | undefined + mocks.runChatLoop.mockImplementationOnce(async (config: any) => { + config.addedMessages.push( + { + role: 'assistant', + content: '', + tool_calls: [{ id: 'call_1', type: 'function', function: { name: 'x', arguments: '{}' } }] + }, + { role: 'tool', tool_call_id: 'call_1', content: 'Tool execution was cancelled by user' } + ) + manager.applyToolStatus('call_1', { declinedByUser: true }) + manager.queueMessage('also tell me the capital of Peru') + manager.sendQueuedMidTurn() + taken = config.takeMidTurnMessage() + markedAfter = manager.queuedSendsMidTurn + return { addedMessages: config.addedMessages } + }) + replyWith('Lima') + + await manager.sendRequest({ instructions: 'deploy it' }) + expect(taken).toBeUndefined() + expect(markedAfter).toBe(false) + expect(mocks.runChatLoop).toHaveBeenCalledTimes(2) + expect( + manager.displayMessages.some( + (m) => m.role === 'user' && m.content === 'also tell me the capital of Peru' + ) + ).toBe(true) + }) + const img = (n: string): AttachedImage => ({ dataUrl: `data:image/png;base64,${n}`, mediaType: 'image/png', @@ -1290,6 +1395,25 @@ describe('AIChatManager queued messages', () => { expect(manager.queuedImages).toEqual([]) }) + it('does not mark a queued image for a model that cannot read it', async () => { + const manager = createManager(createInputMock()) + manager.mode = AIMode.GLOBAL + mocks.tryGetCurrentModel.mockReturnValue({ provider: 'groq', model: 'llama-3.3-70b-versatile' }) + let marked: boolean | undefined + mocks.runChatLoop.mockImplementationOnce(async (config: any) => { + manager.queueMessage('what is in it', [img('a')]) + manager.sendQueuedMidTurn() + marked = manager.queuedSendsMidTurn + const message = { role: 'assistant' as const, content: 'done' } + config.addedMessages.push(message) + return { addedMessages: [message] } + }) + replyWith('ok') + + await manager.sendRequest({ instructions: 'work' }) + expect(marked).toBe(false) + }) + // Attaching is refused on a text-only model, but the model can be switched // after attaching (or a screenshot buffered), and sending the image then fails // the whole turn. The send path re-checks rather than trusting the attach gate. diff --git a/frontend/src/lib/components/copilot/chat/AIChatMessage.svelte b/frontend/src/lib/components/copilot/chat/AIChatMessage.svelte index d006307967..f521fcce1d 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatMessage.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatMessage.svelte @@ -87,9 +87,11 @@ {:else} <div class={twMerge( - 'mb-1 min-w-0', - message.role === 'user' && 'mb-2', - message.role === 'user' && messageIndex > 0 && 'mt-4 mb-6', + 'mb-2 min-w-0', + inGroup && 'mb-1', + message.role === 'user' && 'mb-6', + // mt-4, not mt-6: the message above already brings its own mb-2. + message.role === 'user' && messageIndex > 0 && 'mt-4', isLast && '!mb-12', message.role !== 'user' || !chatHost.supportsMessageEditing ? 'cursor-default' @@ -185,6 +187,7 @@ files to go out). --> {#if message.content.trim() !== ''} <div + data-user-bubble={messageIndex} class="text-xs px-3 py-2 w-fit max-w-[min(32rem,100%)] bg-surface-accent-selected text-accent rounded-lg relative group break-words" > {#each segments(messageDraft(message)) as seg}{#if seg.type === 'text'}<span diff --git a/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte b/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte index 5f4b4a5040..fb65460f2c 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte @@ -17,6 +17,7 @@ copilotInfo, copilotSessionModel, getUserCustomPrompts, + invalidateWorkspaceCopilotInfo, setCopilotInfo, setUserCustomPrompts } from '$lib/aiStore' @@ -192,6 +193,7 @@ requestBody: { ...config, custom_prompts } }) setCopilotInfo(response.effective_ai_config) + invalidateWorkspaceCopilotInfo(workspace) initialPrompt = value customPrompts = { [activeMode]: value } sendUserToast('Workspace AI prompt saved') diff --git a/frontend/src/lib/components/copilot/chat/AppAvailableContextList.svelte b/frontend/src/lib/components/copilot/chat/AppAvailableContextList.svelte index f120c89221..39fcbc47f8 100644 --- a/frontend/src/lib/components/copilot/chat/AppAvailableContextList.svelte +++ b/frontend/src/lib/components/copilot/chat/AppAvailableContextList.svelte @@ -1,4 +1,6 @@ <script lang="ts"> + import { overlayHostActive } from '$lib/components/common/overlayHost.svelte' + const hostActive = overlayHostActive() import { ContextIconMap, type ContextElement } from './context' import { ArrowLeft, ChevronRight, FileCode, Code2, Table2 } from 'lucide-svelte' @@ -95,6 +97,7 @@ } function handleKeyDown(e: KeyboardEvent) { + if (!hostActive()) return if (stringSearch.length > 0) { // Navigation in search view (flat list) if (e.key === 'ArrowDown') { diff --git a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte index 547940bde9..ebea3dbb6a 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte @@ -23,6 +23,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio import { copilotInfo, getUserCustomPrompts, + invalidateWorkspaceCopilotInfo, setCopilotInfo, setUserCustomPrompts } from '$lib/aiStore' @@ -596,6 +597,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio requestBody: { ...config, custom_prompts } }) setCopilotInfo(response.effective_ai_config) + invalidateWorkspaceCopilotInfo(target) workspaceSaved = value workspaceDraft = value sendUserToast('Workspace instructions were saved') diff --git a/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte b/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte index ce931213b5..841966a687 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte @@ -6,6 +6,7 @@ import { thinkingPreferences } from './thinkingPreferences.svelte' import CodeDisplay from './script/CodeDisplay.svelte' import LinkRenderer from './LinkRenderer.svelte' + import MarkdownImage from './MarkdownImage.svelte' import { extractCandidatePaths, remarkWindmillPaths, @@ -98,11 +99,12 @@ }) const candidatePaths = $derived(extractCandidatePaths(message.content)) - const reasoningPlugins = [gfmPlugin(), { renderer: { a: LinkRenderer } }] + const reasoningPlugins = [gfmPlugin(), { renderer: { a: LinkRenderer, img: MarkdownImage } }] const rendererPlugin = { renderer: { pre: CodeDisplay, - a: LinkRenderer + a: LinkRenderer, + img: MarkdownImage } } @@ -174,12 +176,14 @@ {/if} {#if message.content && showActions} - <!-- Kept in flow while invisible, so revealing it on hover does not nudge the message - below. A thinking-only row has no answer to copy, and its run's last answer links the run. --> + <!-- Zero height in the layout (h-4 = -mt-1 + -mb-3): it draws in the answer's bottom + padding and the gap below the turn, so a turn's last answer is spaced like any other + message. A thinking-only row has no answer to copy, and its run's last answer links + the run. --> <div - class="flex items-center gap-2 text-2xs text-tertiary opacity-0 transition-opacity duration-150 group-hover/answer:opacity-100 focus-within:opacity-100" + class="flex items-center gap-2 h-4 -mt-1 -mb-3 text-2xs text-tertiary opacity-0 transition-opacity duration-150 group-hover/answer:opacity-100 focus-within:opacity-100" > - <CopyButton value={message.content} title="Copy answer" class="-ml-1" /> + <CopyButton value={message.content} title="Copy answer" class="-ml-1" btnClasses="h-4" /> {#if timestamp} <span>{timestamp}</span> {/if} diff --git a/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte b/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte index 74e56530b2..d3a9d7982a 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte @@ -35,6 +35,7 @@ callers that already know which section they mean, such as the "+" menu's Manage import Modal2 from '$lib/components/common/modal/Modal2.svelte' import SidebarNavigation from '$lib/components/common/sidebar/SidebarNavigation.svelte' import { logFeatureUsage } from '$lib/utils/featureUsage' + import { SettingsService } from '$lib/gen' import { getAiChatManager } from './aiChatManagerContext' import { summarizeTools } from './agentContext' import AssistantToolsSection from './AssistantToolsSection.svelte' @@ -47,15 +48,24 @@ callers that already know which section they mean, such as the "+" menu's Manage import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import AssistantDangerZoneSection from './AssistantDangerZoneSection.svelte' import { useActingUser } from '$lib/actingUser.svelte' + import { overlayHostActive } from '$lib/components/common/overlayHost.svelte' // Prefilled title marks the issue as AI Sessions feedback for triage. const FEEDBACK_ISSUE_URL = 'https://github.com/windmill-labs/windmill/issues/new?title=' + encodeURIComponent('AI Sessions feedback: ') + // Fetched on first open; until it answers, the link opens without a body. + let version: string | undefined = $state() + let feedbackIssueUrl = $derived( + version + ? FEEDBACK_ISSUE_URL + '&body=' + encodeURIComponent(`Windmill version: ${version}\n\n`) + : FEEDBACK_ISSUE_URL + ) const operatingWorkspace = useOperatingWorkspace() const aiChatManager = getAiChatManager() + const hostActive = overlayHostActive() let isOpen = $state(false) let section = $state<AssistantSettingsSection>('tools') @@ -101,7 +111,8 @@ callers that already know which section they mean, such as the "+" menu's Manage * it would then answer the key it was revealed by — reverting the very draft the * user was brought here to see. */ function onKeydown(event: KeyboardEvent) { - if (!isOpen || event.key !== 'Escape') return + // Hidden hosts stay mounted and still receive window keys — see overlayHost. + if (!isOpen || event.key !== 'Escape' || !hostActive()) return const blocker = blockingSection if (!blocker || blocker === section) return event.preventDefault() @@ -124,7 +135,9 @@ callers that already know which section they mean, such as the "+" menu's Manage // assistant can call here, so it must not shift when the autonomy picker does. // The danger zone writes the workspace's AI config, which only its admins may change. const acting = useActingUser(() => ws) - let isWsAdmin = $derived(!!acting.current && (acting.current.is_admin || acting.current.is_super_admin)) + let isWsAdmin = $derived( + !!acting.current && (acting.current.is_admin || acting.current.is_super_admin) + ) let tools = $derived(summarizeTools(aiChatManager.availableTools)) let providerTools = $derived(aiChatManager.providerTools) @@ -158,6 +171,11 @@ callers that already know which section they mean, such as the "+" menu's Manage focusRoot = undefined section = target isOpen = true + if (!version) { + SettingsService.backendVersion() + .then((v) => (version = v)) + .catch(() => {}) + } refresh() record('open') record(target) @@ -246,7 +264,7 @@ callers that already know which section they mean, such as the "+" menu's Manage unifiedSize="sm" endIcon={{ icon: ExternalLink }} btnClasses="!justify-start !w-full" - href={FEEDBACK_ISSUE_URL} + href={feedbackIssueUrl} target="_blank" > Give feedback @@ -313,9 +331,7 @@ callers that already know which section they mean, such as the "+" menu's Manage <AssistantPermissionsSection {ws} /> </div> {#if isWsAdmin} - <div - class="{section === 'danger' ? 'block' : 'hidden'} grow min-h-0 overflow-y-auto pr-2" - > + <div class="{section === 'danger' ? 'block' : 'hidden'} grow min-h-0 overflow-y-auto pr-2"> <AssistantDangerZoneSection {ws} /> </div> {/if} diff --git a/frontend/src/lib/components/copilot/chat/ChatCollapsibleCard.svelte b/frontend/src/lib/components/copilot/chat/ChatCollapsibleCard.svelte index e5a9989365..11ef941129 100644 --- a/frontend/src/lib/components/copilot/chat/ChatCollapsibleCard.svelte +++ b/frontend/src/lib/components/copilot/chat/ChatCollapsibleCard.svelte @@ -17,6 +17,8 @@ labelMore?: string[] expanded: boolean onToggle: () => void + /** Called once the body has finished opening, when its contents have their final position. */ + onContentShown?: () => void // A card with nothing to reveal keeps the header inert (no chevron, no // hover affordance implying a toggle). toggleable?: boolean @@ -49,6 +51,7 @@ labelMore, expanded, onToggle, + onContentShown, toggleable = true, shimmer = false, settleLabel = false, @@ -77,12 +80,15 @@ <div class={twMerge('font-mono text-xs', className)}> {#snippet labelText(highlight: boolean)} + <!-- One line, cut with an ellipsis: a long name (a script summary) wrapping would push the + status and chevron off the row's single line. --> <span class={twMerge( - 'text-secondary font-medium text-2xs', + 'text-secondary font-medium text-2xs truncate min-w-0', labelClass, highlight && 'text-emphasis' )} + title={highlight ? undefined : `${shown.prefix ? `${shown.prefix} ` : ''}${shown.label}`} > {#if shown.prefix}<span class="font-normal text-secondary">{shown.prefix}</span > {/if}{shown.label} @@ -161,6 +167,7 @@ {#if expanded && children} <div transition:slide={{ duration: 150 }} + onintroend={onContentShown} class={twMerge('border border-border-light rounded-md bg-surface p-3', contentClass)} > {@render children()} diff --git a/frontend/src/lib/components/copilot/chat/ChatCommandPicker.svelte b/frontend/src/lib/components/copilot/chat/ChatCommandPicker.svelte index 5c507deb33..09660e7059 100644 --- a/frontend/src/lib/components/copilot/chat/ChatCommandPicker.svelte +++ b/frontend/src/lib/components/copilot/chat/ChatCommandPicker.svelte @@ -1,4 +1,6 @@ <script lang="ts"> + import { overlayHostActive } from '$lib/components/common/overlayHost.svelte' + const hostActive = overlayHostActive() import DrillPicker from '$lib/components/DrillPicker.svelte' import type { DrillLeaf, DrillNode } from '$lib/components/drillPicker' import type { ChatCommandItem } from './global/core' @@ -55,7 +57,7 @@ } function onDocumentKeydown(e: KeyboardEvent) { - if (e.key === 'Escape' && !e.defaultPrevented) { + if (hostActive() && e.key === 'Escape' && !e.defaultPrevented) { setShowing?.(false) } } diff --git a/frontend/src/lib/components/copilot/chat/ChatContextPicker.svelte b/frontend/src/lib/components/copilot/chat/ChatContextPicker.svelte index 2a2ce5b825..6fd5395683 100644 --- a/frontend/src/lib/components/copilot/chat/ChatContextPicker.svelte +++ b/frontend/src/lib/components/copilot/chat/ChatContextPicker.svelte @@ -19,6 +19,8 @@ On a workspace-leaf pick, emits a reference-only `WorkspaceScriptElement` / Content is materialized at message-prep time by `AIChatManager` — see PR #9216. --> <script lang="ts"> + import { overlayHostActive } from '$lib/components/common/overlayHost.svelte' + const hostActive = overlayHostActive() import { Database, Diff, FileText, Folder, Layers } from 'lucide-svelte' import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte' import FlowModuleIcon from '$lib/components/flows/FlowModuleIcon.svelte' @@ -41,6 +43,7 @@ Content is materialized at message-prep time by `AIChatManager` — see PR #9216 ContextIconMap, withFolderContextLeaves, type ContextElement, + type WorkspaceAgentElement, type WorkspaceAppElement, type WorkspaceFlowElement, type WorkspaceScriptElement @@ -100,12 +103,12 @@ Content is materialized at message-prep time by `AIChatManager` — see PR #9216 } // Workspace state shared with WorkspaceItemDrillPicker via the loader. - // Flows and scripts everywhere; raw apps only in GLOBAL chat, where the - // raw-app tool surface lets the model act on the reference. Visual apps stay + // Flows and scripts everywhere; raw apps and agents only in GLOBAL chat, where + // its tools let the model act on the reference. Visual apps stay // excluded — they're frontends, not code units (filtered out below, where the // 'app' kind is narrowed to raw apps before tree-building). const WORKSPACE_KINDS = $derived<WorkspaceItemKind[]>( - aiChatManager.mode === AIMode.GLOBAL ? ['flow', 'script', 'app'] : ['flow', 'script'] + aiChatManager.mode === AIMode.GLOBAL ? ['flow', 'script', 'app', 'agent'] : ['flow', 'script'] ) const loader = useWorkspaceItemsLoader( () => $operatingWorkspace, @@ -328,6 +331,15 @@ Content is materialized at message-prep time by `AIChatManager` — see PR #9216 deletable: true } onSelectWorkspaceItem(element) + } else if (d.kind === 'agent') { + const element: WorkspaceAgentElement & { deletable: boolean } = { + type: 'workspace_agent', + path: d.path, + title: d.path, + summary: d.summary, + deletable: true + } + onSelectWorkspaceItem(element) } } else if (d.type === 'workspace_folder') { // A folder is a workspace reference like an item, never in availableContext. @@ -366,7 +378,7 @@ Content is materialized at message-prep time by `AIChatManager` — see PR #9216 // claimed the event (defensive — melt-ui doesn't currently // preventDefault on Esc, but a future host might). function onDocumentKeydown(e: KeyboardEvent) { - if (e.key === 'Escape' && !e.defaultPrevented) { + if (hostActive() && e.key === 'Escape' && !e.defaultPrevented) { setShowing?.(false) } } diff --git a/frontend/src/lib/components/copilot/chat/ContextElementBadge.svelte b/frontend/src/lib/components/copilot/chat/ContextElementBadge.svelte index aaab23f38f..dd94b076ea 100644 --- a/frontend/src/lib/components/copilot/chat/ContextElementBadge.svelte +++ b/frontend/src/lib/components/copilot/chat/ContextElementBadge.svelte @@ -38,6 +38,7 @@ const COMPACT_TYPES = new Set([ 'app_dom_selector', 'workspace_app', + 'workspace_agent', 'workspace_script', 'workspace_flow', 'attached_file' diff --git a/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte b/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte index 4d3080386d..360424ce05 100644 --- a/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte +++ b/frontend/src/lib/components/copilot/chat/ContextTextarea.svelte @@ -43,7 +43,8 @@ selectedContext: ContextElement[] placeholder: string disabled: boolean - onSendRequest: () => void + /** `withModifier`: sent with Ctrl or ⌘ held. */ + onSendRequest: (options: { withModifier: boolean }) => void onAddContext: (contextElement: ContextElement) => void /** Called when the user deletes a previously-inserted `@title` mention * from the textarea. The host should drop the matching entry from @@ -753,7 +754,11 @@ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault() - onSendRequest() + const withModifier = e.ctrlKey || e.metaKey + // Pages bind their own Ctrl/⌘+Enter on the window (the script editor runs its test), + // and would act on this press too. + if (withModifier) e.stopPropagation() + onSendRequest({ withModifier }) } } diff --git a/frontend/src/lib/components/copilot/chat/HistoryManager.svelte.ts b/frontend/src/lib/components/copilot/chat/HistoryManager.svelte.ts index 7843169dd9..41a2b4acca 100644 --- a/frontend/src/lib/components/copilot/chat/HistoryManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/HistoryManager.svelte.ts @@ -51,6 +51,9 @@ interface ChatSchema extends IDBSchema { // in-flight job's tray row and completion survive a reload. Absent on // chats predating this feature. Persisted out-of-band like modifiedItems. backgroundJobs?: ChatJob[] + // Notes queued for the model's next turn (see AIChatManager.queueModelNote), + // so one queued before a reload still reaches it. Written by setModelNotes. + modelNotes?: string[] } indexes: { 'by-session': string } } @@ -328,6 +331,7 @@ export default class HistoryManager { contextUsage?: PersistedContextUsage modifiedItems?: string[] backgroundJobs?: ChatJob[] + modelNotes?: string[] } > = $state({}) @@ -457,6 +461,19 @@ export default class HistoryManager { }) } + async setModelNotes(chatId: string, notes: string[]) { + const existing = this.savedChats[chatId] + if (!existing) return + const updated = { ...$state.snapshot(existing), modelNotes: notes } + this.savedChats = { ...this.savedChats, [chatId]: updated } + await this.enqueueDbWrite(async (db) => { + await db.put('chats', updated) + if (updated.sessionId) { + markSessionDirty(updated.sessionId, chatId, emailOfScopedKey(DB_NAME, db.name)) + } + }) + } + getPastChats() { return this.pastChats } @@ -704,7 +721,11 @@ export default class HistoryManager { ? { backgroundJobs: $state.snapshot(this.savedChats[this.currentChatId].backgroundJobs) } - : {}) + : {}), + // Only setModelNotes changes this field, so every save keeps what it last wrote. + ...(this.savedChats[this.currentChatId]?.modelNotes !== undefined + ? { modelNotes: $state.snapshot(this.savedChats[this.currentChatId].modelNotes) } + : {}) } // The mirror mirrors what the DB holds (refs — the snapshot is // dehydrated below before either sees it): a reopened chat hydrates diff --git a/frontend/src/lib/components/copilot/chat/MarkdownImage.svelte b/frontend/src/lib/components/copilot/chat/MarkdownImage.svelte new file mode 100644 index 0000000000..1f5320d91c --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/MarkdownImage.svelte @@ -0,0 +1,37 @@ +<script lang="ts"> + import { ImageOff } from 'lucide-svelte' + import { safeHref } from '$lib/utils/safeHref' + import { hasUntrustedImages, isLocalImageSrc } from './untrustedImages' + + type Props = { + src?: string + alt?: string + title?: string + width?: string | number + height?: string | number + } + let { src, alt, title, width, height }: Props = $props() + + const untrusted = hasUntrustedImages() + const blocked = $derived(untrusted && !isLocalImageSrc(src)) + const href = $derived(blocked ? safeHref(src, window.location.href) : undefined) + const label = $derived(alt || title || src || 'image') +</script> + +{#if !blocked} + <img {src} {alt} {title} {width} {height} /> +{:else if href} + <a + {href} + target="_blank" + rel="noopener noreferrer" + class="inline-flex items-center gap-1" + title="Image from {href}, not loaded here" + > + <ImageOff size={12} class="shrink-0" />{label} + </a> +{:else} + <span class="inline-flex items-center gap-1 text-tertiary"> + <ImageOff size={12} class="shrink-0" />{label} + </span> +{/if} diff --git a/frontend/src/lib/components/copilot/chat/MarkdownImageSource.svelte b/frontend/src/lib/components/copilot/chat/MarkdownImageSource.svelte new file mode 100644 index 0000000000..cfb53003c5 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/MarkdownImageSource.svelte @@ -0,0 +1,14 @@ +<script lang="ts"> + import { hasUntrustedImages } from './untrustedImages' + + type Props = { srcSet?: string; srcset?: string; media?: string; type?: string } + let { srcSet, srcset, media, type }: Props = $props() + + // A `<picture>` picks the first `<source>` that matches over its `<img>`, so a source left in + // untrusted markup would load an outside image past MarkdownImage's check of the `<img>`. + const untrusted = hasUntrustedImages() +</script> + +{#if !untrusted} + <source srcset={srcSet ?? srcset} {media} {type} /> +{/if} diff --git a/frontend/src/lib/components/copilot/chat/QueuedMessageChip.svelte b/frontend/src/lib/components/copilot/chat/QueuedMessageChip.svelte index b80fa17bb1..26034fe4f4 100644 --- a/frontend/src/lib/components/copilot/chat/QueuedMessageChip.svelte +++ b/frontend/src/lib/components/copilot/chat/QueuedMessageChip.svelte @@ -1,17 +1,52 @@ <script lang="ts"> - import { Button } from '$lib/components/common' + import { Button, Kbd } from '$lib/components/common' import { FileText, X } from 'lucide-svelte' import ContextElementBadge from './ContextElementBadge.svelte' import { contextElementKey } from './context' import { getChatViewHost } from './chatViewHost' + import { isMac } from '$lib/utils' + + interface Props { + /** The composer's textarea has focus. */ + composerFocused: boolean + onFocusComposer: () => void + } + + let { composerFocused, onFocusComposer }: Props = $props() // The single message typed while a turn was streaming, waiting to be - // auto-sent when the turn finishes. Rendered above the whole input stack + // auto-sent when the turn finishes (or, marked with Ctrl/⌘+Enter, into the + // turn once its running tools finish). Rendered above the whole input stack // (session bars, context badges, textarea) so it reads as "next in the - // conversation". Pressing Enter again appends another line to it; clicking - // the chip body (its X, or ArrowUp in the empty input) removes it and - // restores its content into the input so nothing is lost. + // conversation". Pressing Enter again appends another line to it; its X (or + // ArrowUp in the empty input) removes it and restores its content into the + // input so nothing is lost, and a click on the card focuses the input. const chatHost = getChatViewHost() + + type Hint = 'sendsMidTurn' | 'stop' | 'midTurn' | 'edit' + + // Only while a turn runs: Esc does nothing once it has finished, and the queue is + // about to auto-send anyway. Key hints show only while the composer has focus, the + // only place ↑ and Ctrl/⌘+Enter act. + const hints = $derived.by(() => { + const list: Hint[] = [] + if (!chatHost.loading) return list + if (chatHost.queuedSendsMidTurn) { + list.push('sendsMidTurn') + } else if (composerFocused) { + if (chatHost.stopSendsQueuedMessage) list.push('stop') + if (chatHost.supportsMidTurnMessages) list.push('midTurn') + } + if (composerFocused) list.push('edit') + return list + }) + + // A press on the card leaves focus in the composer: a blur would hide the hint row + // and move the card under the pointer before the click lands, so a click on a + // context badge would miss its preview popover. + function keepComposerFocus(e: MouseEvent) { + e.preventDefault() + } </script> <!-- Attachment-only and context-only queues have empty text; without their @@ -21,83 +56,110 @@ those stay visible in the composer, and repeating them would read as two selections. --> {#if chatHost.queuedMessage || chatHost.queuedImages.length > 0 || chatHost.queuedFiles.length > 0 || chatHost.queuedBlobs.length > 0 || (chatHost.queuedContext?.length ?? 0) > 0} - <!-- The body and the X are sibling buttons for the same action (an X inside a - clickable chip would be a nested interactive control, invalid ARIA). --> + <!-- The body and the X are sibling buttons (an X inside a clickable chip would be a + nested interactive control, invalid ARIA). --> <div - class="mb-1 flex flex-row items-start gap-1 rounded-md bg-surface-input px-3 py-2 opacity-60 hover:opacity-100" + class="mb-1 rounded-md bg-surface-input px-3 py-2 opacity-80 hover:opacity-100" + role="presentation" + onmousedown={keepComposerFocus} > - {#if chatHost.queuedMessage || chatHost.queuedImages.length > 0 || chatHost.queuedFiles.length > 0 || chatHost.queuedBlobs.length > 0} - <button - type="button" - class="min-w-0 grow text-left cursor-pointer" - title={chatHost.queuedMessage} - aria-label="Remove queued message and put it back in the input" - onclick={() => chatHost.dequeueMessage()} - > - {#if chatHost.queuedImages.length > 0} - <div class="flex flex-row flex-wrap gap-1 {chatHost.queuedMessage ? 'mb-1' : ''}"> - {#each chatHost.queuedImages as image, i (i)} - <img - src={image.dataUrl} - alt={image.name ?? 'queued image'} - class="h-6 w-6 object-cover rounded border border-border-light" - /> - {/each} - </div> - {/if} - {#if chatHost.queuedFiles.length > 0} - <div class="flex flex-row flex-wrap gap-1 {chatHost.queuedMessage ? 'mb-1' : ''}"> - {#each chatHost.queuedFiles as file, i (i)} - <span - class="flex flex-row items-center gap-1 px-1.5 rounded border border-border-light text-2xs text-secondary max-w-36" - title={file.name} - > - <FileText size={10} class="shrink-0" /> - <span class="truncate min-w-0">{file.name}</span> - </span> - {/each} - </div> - {/if} - {#if chatHost.queuedBlobs.length > 0} - <!-- Blobs are the same chip as files: a host that forwards bytes verbatim - queues them here instead, and a queue of them alone must still show. --> - <div class="flex flex-row flex-wrap gap-1 {chatHost.queuedMessage ? 'mb-1' : ''}"> - {#each chatHost.queuedBlobs as blob, i (i)} - <span - class="flex flex-row items-center gap-1 px-1.5 rounded border border-border-light text-2xs text-secondary max-w-36" - title={blob.name} - > - <FileText size={10} class="shrink-0" /> - <span class="truncate min-w-0">{blob.name}</span> - </span> - {/each} - </div> - {/if} - {#if chatHost.queuedMessage} - <p class="text-xs text-secondary whitespace-pre-wrap line-clamp-2"> - {chatHost.queuedMessage} - </p> - {/if} - </button> - {:else if chatHost.queuedContext?.length} - <!-- Context badges are interactive themselves (popover preview), so a - context-only queue gets a plain row instead of the clickable body — - nesting the badges in it would be invalid ARIA and a badge click - would dequeue out from under the opening popover. The X (and - ArrowUp in the empty input) still restores the queue. --> - <div class="min-w-0 grow flex flex-row flex-wrap gap-1"> - {#each chatHost.queuedContext as element (contextElementKey(element))} - <ContextElementBadge contextElement={element} compact /> + <div class="flex flex-row items-start gap-1"> + {#if chatHost.queuedMessage || chatHost.queuedImages.length > 0 || chatHost.queuedFiles.length > 0 || chatHost.queuedBlobs.length > 0} + <button + type="button" + class="min-w-0 grow text-left cursor-pointer" + title={chatHost.queuedMessage} + aria-label="Focus the message input" + onclick={onFocusComposer} + > + {#if chatHost.queuedImages.length > 0} + <div class="flex flex-row flex-wrap gap-1 {chatHost.queuedMessage ? 'mb-1' : ''}"> + {#each chatHost.queuedImages as image, i (i)} + <img + src={image.dataUrl} + alt={image.name ?? 'queued image'} + class="h-6 w-6 object-cover rounded border border-border-light" + /> + {/each} + </div> + {/if} + {#if chatHost.queuedFiles.length > 0} + <div class="flex flex-row flex-wrap gap-1 {chatHost.queuedMessage ? 'mb-1' : ''}"> + {#each chatHost.queuedFiles as file, i (i)} + <span + class="flex flex-row items-center gap-1 px-1.5 rounded border border-border-light text-2xs text-secondary max-w-36" + title={file.name} + > + <FileText size={10} class="shrink-0" /> + <span class="truncate min-w-0">{file.name}</span> + </span> + {/each} + </div> + {/if} + {#if chatHost.queuedBlobs.length > 0} + <!-- Blobs are the same chip as files: a host that forwards bytes verbatim + queues them here instead, and a queue of them alone must still show. --> + <div class="flex flex-row flex-wrap gap-1 {chatHost.queuedMessage ? 'mb-1' : ''}"> + {#each chatHost.queuedBlobs as blob, i (i)} + <span + class="flex flex-row items-center gap-1 px-1.5 rounded border border-border-light text-2xs text-secondary max-w-36" + title={blob.name} + > + <FileText size={10} class="shrink-0" /> + <span class="truncate min-w-0">{blob.name}</span> + </span> + {/each} + </div> + {/if} + {#if chatHost.queuedMessage} + <p class="text-xs !font-normal text-secondary whitespace-pre-wrap line-clamp-2"> + {chatHost.queuedMessage} + </p> + {/if} + </button> + {:else if chatHost.queuedContext?.length} + <!-- Context badges are interactive themselves (popover preview), so a + context-only queue gets a plain row instead of the clickable body — + nesting the badges in it would be invalid ARIA. The X (and ArrowUp + in the empty input) still restores the queue. --> + <div class="min-w-0 grow flex flex-row flex-wrap gap-1" data-context-badges> + {#each chatHost.queuedContext as element (contextElementKey(element))} + <ContextElementBadge contextElement={element} compact /> + {/each} + </div> + {/if} + <Button + variant="subtle" + unifiedSize="xs" + iconOnly + title="Remove queued message and put it back in the input" + startIcon={{ icon: X }} + onClick={() => { + chatHost.dequeueMessage() + onFocusComposer() + }} + /> + </div> + {#if hints.length > 0} + <!-- One nowrap group per hint: the row wraps in a narrow panel, and must not + leave a key at the end of one line and its label on the next. --> + <div class="mt-1 flex flex-row flex-wrap items-center gap-1 text-2xs text-hint"> + {#each hints as hint, i (hint)} + <span class="flex items-center gap-1 whitespace-nowrap"> + {#if hint === 'sendsMidTurn'} + Sends when the running tools finish + {:else if hint === 'stop'} + <Kbd small>Esc</Kbd> to stop and send + {:else if hint === 'midTurn'} + <Kbd small isModifier>{isMac() ? '⌘' : 'Ctrl'}</Kbd><Kbd small>Enter</Kbd> to send without + stopping + {:else} + <Kbd small>↑</Kbd> to edit + {/if} + {#if i < hints.length - 1}·{/if} + </span> {/each} </div> {/if} - <Button - variant="subtle" - unifiedSize="xs" - iconOnly - title="Remove queued message and put it back in the input" - startIcon={{ icon: X }} - on:click={() => chatHost.dequeueMessage()} - /> </div> {/if} diff --git a/frontend/src/lib/components/copilot/chat/RunScriptCard.svelte b/frontend/src/lib/components/copilot/chat/RunScriptCard.svelte index 554ce126d2..f7a6181f9a 100644 --- a/frontend/src/lib/components/copilot/chat/RunScriptCard.svelte +++ b/frontend/src/lib/components/copilot/chat/RunScriptCard.svelte @@ -2,7 +2,8 @@ import { onMount } from 'svelte' import { cubicOut } from 'svelte/easing' import { prefersReducedMotion } from 'svelte/motion' - import { Ban, Loader2, TimerOff } from 'lucide-svelte' + import { Ban, Loader2, Maximize2, TimerOff } from 'lucide-svelte' + import Modal from '$lib/components/common/modal/Modal.svelte' import { twMerge } from 'tailwind-merge' import { Button, Tab, Tabs } from '$lib/components/common' import Toggle from '$lib/components/Toggle.svelte' @@ -339,22 +340,33 @@ // against it; logs and a result stand on the body's own ground and take it cleanly. const fadeBody = $derived(!rawView && (activeTab === 'logs' || activeTab === 'outcome')) + // The full screen copy of the body, rendered in the modal. + let modalBodyEl: HTMLElement | undefined = $state() + const modalFades = scrollFades() + // Keyed by call id for the same reason as the tab and the JSON toggle. + let fullscreenId = $state<string | undefined>(undefined) + // One scroll region serves every tab, so a switch has to place it: logs open on their // end, which is where a run is read from, and everything else on its start — otherwise // the tab opened after the logs would begin part-way down its own content. - $effect(() => { + // One effect per copy: a shared one would re-place the card each time the modal mounts or + // unmounts, and the card would lose the place the user scrolled it to. + function placeScroll(el: HTMLElement | undefined) { void rawView - if (!bodyEl) return - bodyEl.scrollTop = activeTab === 'logs' && !rawView ? bodyEl.scrollHeight : 0 - }) + if (el) el.scrollTop = activeTab === 'logs' && !rawView ? el.scrollHeight : 0 + } + $effect(() => placeScroll(bodyEl)) + $effect(() => placeScroll(modalBodyEl)) // And stay on the end while the job writes: a log stream the user has to scroll to // read is not following the run. - $effect(() => { + function followLogs(el: HTMLElement | undefined) { void logs - if (!bodyEl || rawView || activeTab !== 'logs' || !running) return - bodyEl.scrollTop = bodyEl.scrollHeight - }) + if (!el || rawView || activeTab !== 'logs' || !running) return + el.scrollTop = el.scrollHeight + } + $effect(() => followLogs(bodyEl)) + $effect(() => followLogs(modalBodyEl)) // Ticks only while this card has a job in flight, so a transcript of settled runs // keeps no timers at all. @@ -546,7 +558,7 @@ headerRight={previewTarget ? previewChip : undefined} class="scroll-mb-8" labelClass="font-main font-medium text-primary" - contentClass="p-0 overflow-hidden" + contentClass="p-0 overflow-hidden font-main" > {#if formInPreview} <div class="px-3 py-2 text-2xs leading-4 text-hint"> @@ -555,232 +567,274 @@ {:else if pending && runForm} <RunArgsFormDisplay toolCallId={message.tool_call_id} {runForm} /> {:else} - <!-- One region holding the strip and the body, fixed so the card is the same size on every + <!-- Rendered twice: in the card and, full screen, in the modal below. Each copy has its own + scroll region and fades; the tab and JSON toggle are the card's, shared by both. --> + {#snippet runBody(inModal: boolean)} + {@const f = inModal ? modalFades : fades} + <!-- One region holding the strip and the body, fixed so the card is the same size on every tab — a cap would not do it, since the body is a scroll region and a max-height silently beats flex-grow. The raw view takes that height as a floor instead: its blocks scroll on their own, as an ordinary tool call's do, so a scroller around them - would be one too many. --> - <div - class={twMerge( - 'relative flex flex-col', - rawView ? 'min-h-[20rem]' : jobPending ? '' : 'h-[20rem]' - )} - > - <!-- The tabs go in raw view — they name the parts of the body, and the raw call is not + would be one too many. The modal fills its own height on every view. --> + <div + class={twMerge( + 'relative flex flex-col', + inModal ? 'min-h-0 flex-1' : rawView ? 'min-h-[20rem]' : jobPending ? '' : 'h-[20rem]' + )} + > + <!-- The tabs go in raw view — they name the parts of the body, and the raw call is not one of them — while the strip stays, since the JSON toggle lives there. Hence its fixed height: a row sized by its contents would step every time the tabs leave, and the tighter Tab padding below is what fits a label inside that height. --> - <Tabs - selected={activeTab} - on:selected={(e) => (userTab = { id: message.tool_call_id, value: e.detail })} - class="h-8 px-3 font-main" - wrapperClass="shrink-0" - slidingIndicator - > - {#if !rawView && !jobPending} - {#each tabs as tab (tab.value)} - <!-- The tab widens in first and the bar follows it, because a run adds its tabs as + <Tabs + selected={activeTab} + on:selected={(e) => (userTab = { id: message.tool_call_id, value: e.detail })} + class="h-8 px-3 font-main" + wrapperClass="shrink-0" + slidingIndicator + > + {#if !rawView && !jobPending} + {#each tabs as tab (tab.value)} + <!-- The tab widens in first and the bar follows it, because a run adds its tabs as it produces them: landing the selection on a tab in the frame it appears reads as one unexplained jump. `border-b-0` because the bar is the selection now. Size only: Tab's own colour and weight mark the selection, and this class lands after them in its twMerge, so a colour here would silently win. --> - <span class="inline-flex overflow-hidden" in:growIn={{ live: liveStrip }}> - <Tab - value={tab.value} - label={tab.label} - class="border-b-0 py-0.5 text-2xs leading-4" - exact - > - {#snippet extra()} - {#if tab.value === 'logs' && logLineCount > 0} - <span class="text-2xs text-hint">{logLineCount}</span> - {/if} - {/snippet} - </Tab> - </span> - {/each} - {/if} - <div class="ml-auto flex items-center pl-2"> - <Toggle - checked={rawView} - on:change={(e) => (jsonView = { id: message.tool_call_id, on: e.detail })} - size="2xs" - options={{ right: 'JSON', rightTooltip: 'Show this call as raw JSON' }} - lightMode - /> - </div> - </Tabs> - - <!-- Logs sit on the softer surface, the way program output is shown everywhere else. - The raw view keeps the card's own, as an ordinary tool call has it. --> - <div - bind:this={bodyEl} - use:fades.container - onscroll={fades.measure} - class={twMerge( - 'min-h-0 flex-1 px-3 py-2', - rawView ? '' : 'overflow-auto', - !rawView && !jobPending && activeTab === 'logs' ? 'bg-surface-secondary/50' : '' - )} - > - <!-- min-h-full rather than h-full: the states that centre themselves need the height, - and a box that always filled it would measure as never scrollable. --> - <div use:fades.content class="flex min-h-full flex-col"> - {#if rawView} - <div class="space-y-3"> - <!-- Each block scrolls on its own, so each fades on its own. --> - <ToolContentDisplay title="Parameters" content={message.parameters} showFade /> - <ToolContentDisplay title="Logs" content={message.logs} tail showFade /> - <ToolContentDisplay - title="Result" - content={message.result} - error={message.error} - showFade + <span class="inline-flex overflow-hidden" in:growIn={{ live: liveStrip }}> + <Tab + value={tab.value} + label={tab.label} + class="border-b-0 py-0.5 text-2xs leading-4" + exact + > + {#snippet extra()} + {#if tab.value === 'logs' && logLineCount > 0} + <span class="text-2xs text-hint">{logLineCount}</span> + {/if} + {/snippet} + </Tab> + </span> + {/each} + {/if} + <div class="ml-auto flex items-center gap-1 pl-2"> + <Toggle + checked={rawView} + on:change={(e) => (jsonView = { id: message.tool_call_id, on: e.detail })} + size="2xs" + options={{ right: 'JSON', rightTooltip: 'Show this call as raw JSON' }} + lightMode + /> + {#if !inModal} + <Button + variant="subtle" + unifiedSize="2xs" + startIcon={{ icon: Maximize2 }} + iconOnly + title="Open full screen" + onClick={() => (fullscreenId = message.tool_call_id)} /> - </div> - {:else if jobPending} - <!-- The strip above stays whatever the job does: the call's own result is already + {/if} + </div> + </Tabs> + + <!-- Logs sit on the softer surface, the way program output is shown everywhere else. + The raw view keeps the card's own, as an ordinary tool call has it. --> + <div + {@attach (el) => { + if (inModal) modalBodyEl = el + else bodyEl = el + return () => { + if (inModal) modalBodyEl = undefined + else bodyEl = undefined + } + }} + use:f.container + onscroll={f.measure} + class={twMerge( + 'min-h-0 flex-1 px-3 py-2', + rawView && !inModal ? '' : 'overflow-auto', + !rawView && !jobPending && activeTab === 'logs' ? 'bg-surface-secondary/50' : '' + )} + > + <!-- min-h-full rather than h-full: the states that centre themselves need the height, + and a box that always filled it would measure as never scrollable. --> + <div use:f.content class="flex min-h-full flex-col"> + {#if rawView} + <div class="space-y-3"> + <!-- Each block scrolls on its own, so each fades on its own. --> + <ToolContentDisplay title="Parameters" content={message.parameters} showFade /> + <ToolContentDisplay title="Logs" content={message.logs} tail showFade /> + <ToolContentDisplay + title="Result" + content={message.result} + error={message.error} + showFade + /> + </div> + {:else if jobPending} + <!-- The strip above stays whatever the job does: the call's own result is already in the transcript, and the JSON toggle is how it is read. --> - <div class="text-2xs leading-4 text-hint"> - {#if fetchFailed === message.tool_call_id} - This run could not be read. It may have been deleted, or be in another workspace. - Its result is on the JSON toggle. - {:else} - <span class="inline-flex items-center gap-1.5"> - <Loader2 class="h-3 w-3 animate-spin" /> - Loading this run... - </span> - {/if} - </div> - {:else} - <!-- Keyed on the tab so the body arrives rather than cuts. One region serves every + <div class="text-2xs leading-4 text-hint"> + {#if fetchFailed === message.tool_call_id} + This run could not be read. It may have been deleted, or be in another workspace. + Its result is on the JSON toggle. + {:else} + <span class="inline-flex items-center gap-1.5"> + <Loader2 class="h-3 w-3 animate-spin" /> + Loading this run... + </span> + {/if} + </div> + {:else} + <!-- Keyed on the tab so the body arrives rather than cuts. One region serves every tab, so only the incoming pane moves: overlapping them would ask this scroller to hold two at once. --> - {#key activeTab} - <div class="flex min-h-full flex-1 flex-col" in:enterPane> - {#if activeTab === 'input'} - <!-- What the runs page shows a finished job's arguments as: the operator has already + {#key activeTab} + <div class="flex min-h-full flex-1 flex-col" in:enterPane> + {#if activeTab === 'input'} + <!-- What the runs page shows a finished job's arguments as: the operator has already read this table. The job id is what lets it fetch arguments too big to have been persisted with the card. --> - <JobArgs - args={parameters} - id={job?.jobId} - workspace={job?.workspace} - disableExpand - /> - {:else if activeTab === 'logs'} - {#if logs.trim()} - {#if logs.length >= MAX_LOG_LENGTH} - <p class="mb-1 text-2xs text-tertiary"> - Tail of the logs, the last {MAX_LOG_LENGTH} characters. + <JobArgs + args={parameters} + id={job?.jobId} + workspace={job?.workspace} + disableExpand + /> + {:else if activeTab === 'logs'} + {#if logs.trim()} + {#if logs.length >= MAX_LOG_LENGTH} + <p class="mb-1 text-2xs text-tertiary"> + Tail of the logs, the last {MAX_LOG_LENGTH} characters. + </p> + {/if} + <pre class="whitespace-pre-wrap break-words font-mono text-2xs text-primary" + >{logs}</pre + > + {:else} + <p class="text-2xs text-tertiary"> + {inspectedJob?.logsFailed + ? 'Logs could not be read.' + : running + ? 'No logs yet.' + : 'No logs.'} </p> {/if} - <pre class="whitespace-pre-wrap break-words font-mono text-2xs text-primary" - >{logs}</pre - > - {:else} - <p class="text-2xs text-tertiary"> - {inspectedJob?.logsFailed - ? 'Logs could not be read.' - : running - ? 'No logs yet.' - : 'No logs.'} - </p> - {/if} - {#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 - </div> - {/if} - <!-- A run the chat started reports its failure on the tool call; an inspected one + {#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 + </div> + {/if} + <!-- A run the chat started reports its failure on the tool call; an inspected one carries it as its result, which the pane below renders the way the run page does. `failed` excludes a cancellation, which also leaves an error on the message but owns its own pane. --> - {:else if !inspected && failed} - <pre - class="whitespace-pre-wrap break-words font-mono text-2xs text-red-700 dark:text-red-300" - >{message.error}</pre - > - {:else if streaming} - <!-- The same renderer as a landed result, handed the partial: it is the one that + {:else if !inspected && failed} + <pre + class="whitespace-pre-wrap break-words font-mono text-2xs text-red-700 dark:text-red-300" + >{message.error}</pre + > + {:else if streaming} + <!-- The same renderer as a landed result, handed the partial: it is the one that knows how to show a result arriving in pieces. --> - <DisplayResult - result={undefined} - result_stream={resultStream} - jobId={job?.jobId} - workspaceId={job?.workspace} - disableExpand - hideAsJson - /> - {:else if resultValue !== undefined} - <!-- The run page's own renderer, not a second one invented for the chat: it handles + <DisplayResult + result={undefined} + result_stream={resultStream} + jobId={job?.jobId} + workspaceId={job?.workspace} + disableExpand + hideAsJson + /> + {:else if resultValue !== undefined} + <!-- The run page's own renderer, not a second one invented for the chat: it handles markdown, tables, images and deep nesting without the card guessing at the shape, and reaches the job through jobId/workspace for an S3 preview. `disableExpand` drops its toolbar and `hideAsJson` its Pretty/JSON switch, which the row already owns. --> - <DisplayResult - result={resultValue} - jobId={job?.jobId} - workspaceId={job?.workspace} - disableExpand - hideAsJson - /> - {:else if canceled} - <!-- All that is left to render is the fact itself: a form cancelled before Run + <DisplayResult + result={resultValue} + jobId={job?.jobId} + workspaceId={job?.workspace} + disableExpand + hideAsJson + /> + {:else if canceled} + <!-- All that is left to render is the fact itself: a form cancelled before Run never reached a job, so there is no result the way a cancelled run has one. --> - <div - class="flex flex-1 flex-col items-center justify-center gap-1.5 px-4 text-center" - > - <Ban class="h-4 w-4 text-tertiary" /> - <p class="text-2xs font-medium leading-4 text-secondary">{cancelReason}</p> - {#if !ran} - <p class="text-2xs leading-4 text-tertiary"> - The inputs it would have run with are on the Inputs tab. - </p> - {/if} - </div> - {:else} - <p class="text-2xs text-tertiary">This run returned no result.</p> - {/if} - </div> - {/key} - {/if} + <div + class="flex flex-1 flex-col items-center justify-center gap-1.5 px-4 text-center" + > + <Ban class="h-4 w-4 text-tertiary" /> + <p class="text-2xs font-medium leading-4 text-secondary">{cancelReason}</p> + {#if !ran} + <p class="text-2xs leading-4 text-tertiary"> + The inputs it would have run with are on the Inputs tab. + </p> + {/if} + </div> + {:else} + <p class="text-2xs text-tertiary">This run returned no result.</p> + {/if} + </div> + {/key} + {/if} + </div> </div> - </div> - <!-- Over the body, not inside it: what is still below fades out, and nothing at the top, + <!-- Over the body, not inside it: what is still below fades out, and nothing at the top, as on the form and on the tool cards. Two layers on the logs, whose ground is the card's surface with the softer one at half strength over it — one gradient would end on the wrong colour and leave a band at the very edge. --> - {#if fades.bottom && fadeBody} - <div - class="pointer-events-none absolute inset-x-0 bottom-0 h-[min(2.5rem,35%)] bg-gradient-to-t from-surface via-surface/60 to-transparent" - ></div> - {#if activeTab === 'logs'} + {#if f.bottom && fadeBody} <div - class="pointer-events-none absolute inset-x-0 bottom-0 h-[min(2.5rem,35%)] bg-gradient-to-t from-surface-secondary/50 via-surface-secondary/30 to-transparent" + class="pointer-events-none absolute inset-x-0 bottom-0 h-[min(2.5rem,35%)] bg-gradient-to-t from-surface via-surface/60 to-transparent" ></div> + {#if activeTab === 'logs'} + <div + class="pointer-events-none absolute inset-x-0 bottom-0 h-[min(2.5rem,35%)] bg-gradient-to-t from-surface-secondary/50 via-surface-secondary/30 to-transparent" + ></div> + {/if} {/if} - {/if} - </div> + </div> - {#if running && chatJob} - <!-- Where the form keeps its own actions, so the button that stops a run and the one + {#if running && chatJob} + <!-- Where the form keeps its own actions, so the button that stops a run and the one that starts it sit in the same corner of the same card. The run page's own cancel button, down to the icon: the operator has already pressed this one. --> - <div class="flex justify-end border-t border-border-light px-3 py-2"> - <Button - variant="accent" - unifiedSize="sm" - destructive - startIcon={{ icon: TimerOff }} - title={`Cancel the ${runnableNoun}`} - onClick={() => aiChatManager.cancelJob(chatJob.jobId)} - > - Cancel - </Button> + <div class="flex justify-end border-t border-border-light px-3 py-2"> + <Button + variant="accent" + unifiedSize="sm" + destructive + startIcon={{ icon: TimerOff }} + title={`Cancel the ${runnableNoun}`} + onClick={() => aiChatManager.cancelJob(chatJob.jobId)} + > + Cancel + </Button> + </div> + {/if} + {/snippet} + + {@render runBody(false)} + + <!-- Modal portals itself out, so declaring it here keeps it beside the snippet it renders + and closes it with the branch: a run that turns back into a form has no card to show. --> + <Modal + bind:open={ + () => fullscreenId === message.tool_call_id, + (v) => (fullscreenId = v ? message.tool_call_id : undefined) + } + title={`${verb} ${runnableName}`} + kind="X" + fillHeight + enterConfirms={false} + class="sm:max-w-none" + > + <div class="flex h-full flex-col overflow-hidden rounded-md border border-border-light"> + {@render runBody(true)} </div> - {/if} + </Modal> {/if} </ChatCollapsibleCard> diff --git a/frontend/src/lib/components/copilot/chat/ToolConfirmationFooter.svelte b/frontend/src/lib/components/copilot/chat/ToolConfirmationFooter.svelte index faf0395bc3..5e3d4048dc 100644 --- a/frontend/src/lib/components/copilot/chat/ToolConfirmationFooter.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolConfirmationFooter.svelte @@ -12,6 +12,7 @@ confirmLabel: string /** Omit for a label-only confirm button. */ confirmIcon?: any + confirmDestructive?: boolean class?: string } @@ -22,6 +23,7 @@ rejectDestructive = false, confirmLabel, confirmIcon, + confirmDestructive = false, class: className }: Props = $props() @@ -48,6 +50,7 @@ <Button variant="accent" unifiedSize="sm" + destructive={confirmDestructive} startIcon={confirmIcon ? { icon: confirmIcon } : undefined} on:click={() => respond(true)} > diff --git a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte index 6f711d4908..c1fac18c7a 100644 --- a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte @@ -40,6 +40,7 @@ import { gfmPlugin } from 'svelte-exmarkdown/gfm' import CodeDisplay from './script/CodeDisplay.svelte' import LinkRenderer from './LinkRenderer.svelte' + import MarkdownImage from './MarkdownImage.svelte' import ToolContentDisplay from './ToolContentDisplay.svelte' import ToolConfirmationFooter from './ToolConfirmationFooter.svelte' import ToolMessageActions from './ToolMessageActions.svelte' @@ -105,7 +106,10 @@ ) // The preview pane's renderers, so a model-written link opens in a new tab either way. - const planPlugins = [gfmPlugin(), { renderer: { pre: CodeDisplay, a: LinkRenderer } }] + const planPlugins = [ + gfmPlugin(), + { renderer: { pre: CodeDisplay, a: LinkRenderer, img: MarkdownImage } } + ] const confirmAction = $derived(TOOL_CONFIRM_ACTIONS[message.confirmAction ?? 'confirm']) @@ -405,6 +409,7 @@ rejectDestructive confirmLabel={confirmAction.label} confirmIcon={confirmAction.icon} + confirmDestructive={confirmAction.destructive} /> {:else if pendingOutOfScope} <OutOfScopeFooter diff --git a/frontend/src/lib/components/copilot/chat/ToolGroupDisplay.svelte b/frontend/src/lib/components/copilot/chat/ToolGroupDisplay.svelte index 77f58438da..a77a7bd691 100644 --- a/frontend/src/lib/components/copilot/chat/ToolGroupDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolGroupDisplay.svelte @@ -6,6 +6,8 @@ import { callFailed, groupHeader, type ToolGroup } from './toolGroups' import McpServerIcon from '$lib/components/mcp/McpServerIcon.svelte' import { resolveMcpServerMark } from '$lib/components/mcp/serverMark' + import { Button } from '$lib/components/common' + import { getChatViewHost } from './chatViewHost' interface Props { group: ToolGroup @@ -14,7 +16,30 @@ let { group, entry }: Props = $props() + const chatHost = getChatViewHost() + let expanded = $state(false) + const rows: Record<number, HTMLElement> = {} + let scrollOnceOpen = false + + function scrollToFailedCall() { + const failed = group.entries.find((e) => e.message.role === 'tool' && callFailed(e.message)) + if (failed) { + // Here rather than at the click: while the group opens above a chat pinned to its end, + // scroll anchoring keeps it at the end, and that scroll turns automatic scroll back on. + chatHost.disableAutomaticScroll() + rows[failed.index]?.scrollIntoView({ block: 'center' }) + } + } + + function revealFailedCall() { + if (expanded) { + scrollToFailedCall() + } else { + scrollOnceOpen = true + expanded = true + } + } const calls = $derived( group.entries.map((e) => e.message).filter((m): m is ToolDisplayMessage => m.role === 'tool') @@ -59,7 +84,16 @@ {#snippet status()} <div class="flex items-center gap-2 shrink-0"> {#if failedCount > 0} - <span class="font-main text-2xs text-red-600 dark:text-red-400">{failedCount} failed</span> + <Button + variant="subtle" + unifiedSize="2xs" + destructive + btnClasses="font-main text-2xs text-red-600 dark:text-red-400 hover:bg-red-100 hover:text-red-800 dark:hover:bg-red-700/40 dark:hover:text-red-100" + title="Show the failed call" + onClick={revealFailedCall} + > + {failedCount} failed + </Button> {/if} {#if previewCard} <ToolPreviewCard card={previewCard} /> @@ -72,7 +106,16 @@ label={header.label} labelMore={header.more} {expanded} - onToggle={() => (expanded = !expanded)} + onToggle={() => { + scrollOnceOpen = false + expanded = !expanded + }} + onContentShown={() => { + if (scrollOnceOpen) { + scrollOnceOpen = false + scrollToFailedCall() + } + }} shimmer={running} settleLabel {liveLine} @@ -83,6 +126,8 @@ contentClass="border-0 border-l rounded-none bg-transparent p-0 pl-2 ml-1.5 mt-0.5" > {#each group.entries as { message, index } (index)} - {@render entry(message, index)} + <div bind:this={rows[index]}> + {@render entry(message, index)} + </div> {/each} </ChatCollapsibleCard> diff --git a/frontend/src/lib/components/copilot/chat/WorkspaceMentionPicker.svelte b/frontend/src/lib/components/copilot/chat/WorkspaceMentionPicker.svelte index b296d78ce8..7d22008fcd 100644 --- a/frontend/src/lib/components/copilot/chat/WorkspaceMentionPicker.svelte +++ b/frontend/src/lib/components/copilot/chat/WorkspaceMentionPicker.svelte @@ -20,6 +20,7 @@ at the workspace root because the parent menu item already names the scope. import { withFolderContextLeaves, type ContextElement, + type WorkspaceAgentElement, type WorkspaceAppElement, type WorkspaceFlowElement, type WorkspaceFolderElement, @@ -42,7 +43,7 @@ at the workspace root because the parent menu item already names the scope. let picker: DrillPickerHandle | undefined = $state() const operatingWorkspace = useOperatingWorkspace() - const WORKSPACE_KINDS: WorkspaceItemKind[] = ['flow', 'script', 'app'] + const WORKSPACE_KINDS: WorkspaceItemKind[] = ['flow', 'script', 'app', 'agent'] const loader = useWorkspaceItemsLoader( () => $operatingWorkspace, () => WORKSPACE_KINDS @@ -93,6 +94,15 @@ at the workspace root because the parent menu item already names the scope. deletable: true } satisfies WorkspaceAppElement & { deletable: boolean } } + if (item.kind === 'agent') { + return { + type: 'workspace_agent', + path: item.path, + title: item.path, + summary: item.summary, + deletable: true + } satisfies WorkspaceAgentElement & { deletable: boolean } + } } function handlePick(leaf: DrillLeaf<LeafData>) { diff --git a/frontend/src/lib/components/copilot/chat/anthropic.ts b/frontend/src/lib/components/copilot/chat/anthropic.ts index ce11b0dade..937fe47ed4 100644 --- a/frontend/src/lib/components/copilot/chat/anthropic.ts +++ b/frontend/src/lib/components/copilot/chat/anthropic.ts @@ -14,6 +14,7 @@ import type { } from '@anthropic-ai/sdk/resources' import type { MessageStream } from '@anthropic-ai/sdk/lib/MessageStream' import type { AIProviderModel } from '$lib/gen' +import type { CopilotInfo } from '$lib/aiStore' import { getProviderAndCompletionConfig, workspaceAIClients } from '../lib' import { applyReasoningToConfig } from '../reasoningRegistry' import { @@ -137,13 +138,15 @@ export async function getAnthropicCompletion( anthropicClient?: Anthropic webSearch?: boolean reasoningEffort?: string + info?: CopilotInfo } ): Promise<MessageStream> { const { provider, config } = getProviderAndCompletionConfig({ messages, stream: true, forceModelProvider: options?.forceModelProvider, - reasoningEffort: options?.reasoningEffort + reasoningEffort: options?.reasoningEffort, + info: options?.info }) const { system, messages: anthropicMessages } = convertOpenAIToAnthropicMessages(messages) let anthropicTools = convertOpenAIToolsToAnthropic(tools) diff --git a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactBody.svelte b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactBody.svelte index 7fd32d3fcd..473f646e81 100644 --- a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactBody.svelte +++ b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactBody.svelte @@ -2,9 +2,12 @@ import type { Component } from 'svelte' import Markdown from 'svelte-exmarkdown' import SimpleEditor from '$lib/components/SimpleEditor.svelte' - import { markdownProse } from '$lib/components/markdownProse' - import { markdownPlugins } from '$lib/components/markdownPlugins' import LinkRenderer from '../LinkRenderer.svelte' + import MarkdownImage from '../MarkdownImage.svelte' + import MarkdownImageSource from '../MarkdownImageSource.svelte' + import { artifactPlugins } from './artifactPlugins' + import '@fontsource-variable/jetbrains-mono/wght.css' + import './artifactDocument.css' interface Props { content: string @@ -25,8 +28,15 @@ // this body also renders what another member wrote. Renderers merge in order, so the chat's // link pill and, when given, its code block sit on top of it. const plugins = $derived([ - ...markdownPlugins, - { renderer: { a: LinkRenderer, ...(pre ? { pre } : {}) } } + ...artifactPlugins, + { + renderer: { + a: LinkRenderer, + img: MarkdownImage, + source: MarkdownImageSource, + ...(pre ? { pre } : {}) + } + } ]) </script> @@ -41,7 +51,9 @@ The negative margin cancels its flow height so it overlays instead of pushing. --> <div class="sticky top-0 z-10 h-4 -mb-4 bg-gradient-to-b from-surface-tertiary to-transparent" ></div> - <div class="pb-4 pt-2 {markdownProse.doc}"> - <Markdown md={content} {plugins} /> + <div class="wm-doc-frame"> + <div class="wm-doc pb-16 pt-8"> + <Markdown md={content} {plugins} /> + </div> </div> {/if} diff --git a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactExportButton.svelte b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactExportButton.svelte index 95de830a29..fc77a02f69 100644 --- a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactExportButton.svelte +++ b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactExportButton.svelte @@ -1,9 +1,11 @@ <script lang="ts"> - import { Check, Copy, Download, FileDown } from 'lucide-svelte' + import { Check, Copy, Download, FileCode, FileDown } from 'lucide-svelte' import { Button } from '$lib/components/common' import { copyToClipboard, download } from '$lib/utils' import { artifactFilename, artifactMimeType, type ArtifactKind } from './artifactsDB' + import { artifactHtmlFile } from './artifactExport' import { printArtifact } from './printArtifact' + import { hasUntrustedImages } from '../untrustedImages' interface Props { name: string @@ -16,6 +18,8 @@ let { name, kind, content, disabled = false, iconOnly = false }: Props = $props() + const untrustedImages = hasUntrustedImages() + let copied = $state(false) async function copyRaw() { if (!(await copyToClipboard(content))) return @@ -40,14 +44,31 @@ onClick: () => download(artifactFilename({ name, kind }), content, artifactMimeType(kind)), disabled }, - // Markdown only: an html artifact is agent-written markup, and printing it would run its + // Markdown only: an html artifact already downloads as .html, and printing it would run its // scripts in this origin. + // No .html for someone else's artifact: the file draws its mermaid here and keeps its + // images' outside URLs, which the shared viewer blocks. + ...(kind === 'md' && !untrustedImages + ? [ + { + label: 'Download as .html', + icon: FileCode, + onClick: async () => + download( + artifactFilename({ name, kind: 'html' }), + await artifactHtmlFile(name, content), + artifactMimeType('html') + ), + disabled + } + ] + : []), ...(kind === 'md' ? [ { label: 'Download as PDF', icon: FileDown, - onClick: () => printArtifact(name, content), + onClick: () => printArtifact(name, content, { untrustedImages }), disabled } ] diff --git a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintBody.svelte b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintBody.svelte index f07c6f643f..dabc15ab9c 100644 --- a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintBody.svelte +++ b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintBody.svelte @@ -1,14 +1,28 @@ <script lang="ts"> import Markdown from 'svelte-exmarkdown' - import { markdownProse } from '$lib/components/markdownProse' - import { markdownPlugins } from '$lib/components/markdownPlugins' + import { artifactPlugins } from './artifactPlugins' import ArtifactPrintCodeBlock from './ArtifactPrintCodeBlock.svelte' + import MarkdownImage from '../MarkdownImage.svelte' + import MarkdownImageSource from '../MarkdownImageSource.svelte' + import { setUntrustedImages } from '../untrustedImages' + import { untrack } from 'svelte' + // These load into the app's page, not the print frame: the frame copies the page's stylesheets. + import '@fontsource-variable/jetbrains-mono/wght.css' + import './artifactDocument.css' - let { content }: { content: string } = $props() + let { content, untrustedImages = false }: { content: string; untrustedImages?: boolean } = + $props() - const plugins = [...markdownPlugins, { renderer: { pre: ArtifactPrintCodeBlock } }] + // Mounted in its own root, so the viewer's context does not reach it: the printing page + // passes it on, or a shared artifact's outside images load while the PDF is prepared. + if (untrack(() => untrustedImages)) setUntrustedImages() + + const plugins = [ + ...artifactPlugins, + { renderer: { pre: ArtifactPrintCodeBlock, img: MarkdownImage, source: MarkdownImageSource } } + ] </script> -<div class={markdownProse.doc}> +<div class="wm-doc"> <Markdown md={content} {plugins} /> </div> diff --git a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintCodeBlock.svelte b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintCodeBlock.svelte index 261b39febf..f495307099 100644 --- a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintCodeBlock.svelte +++ b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactPrintCodeBlock.svelte @@ -1,7 +1,12 @@ <script lang="ts"> import MarkdownCodeBlock from '$lib/components/MarkdownCodeBlock.svelte' + import { hasUntrustedImages } from '../untrustedImages' + + // Someone else's artifact keeps mermaid off, as its viewer does: a diagram can fetch images + // from other hosts without going through MarkdownImage. + const renderMermaid = !hasUntrustedImages() </script> -<!-- The viewer's code block without the chat context its own renderer needs. Mermaid is on as - in the viewer: only the session's own artifacts are exported. --> -<MarkdownCodeBlock renderMermaid lightMermaid /> +<!-- The viewer's code block without the chat context its own renderer needs. Display blocks are + on as in the viewer. --> +<MarkdownCodeBlock {renderMermaid} lightMermaid renderDisplay staticDisplay /> diff --git a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactViewer.svelte b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactViewer.svelte index 8331825ee2..7445ac9b17 100644 --- a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactViewer.svelte +++ b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactViewer.svelte @@ -18,18 +18,22 @@ interface Props { artifact: PersistedArtifact - store: SessionArtifactsStore + /** Absent for a `sharedCopy`, which has no history to read. */ + store?: SessionArtifactsStore /** Version being viewed, or undefined for the current one. Owned by the caller — it * outlives this component, so the viewer must not keep a copy of its own. */ pinned?: number onPin: (version: number | undefined) => void + /** A copy read from someone else's shared session. A share keeps only the latest text, + * so there is no history to pick from, and sharing it again is the author's call. */ + sharedCopy?: boolean } - let { artifact, store, pinned, onPin }: Props = $props() + let { artifact, store, pinned, onPin, sharedCopy = false }: Props = $props() const latest = $derived(currentVersion(artifact)) // Nothing to pick between until a second version exists. - const hasHistory = $derived(latest > 1) + const hasHistory = $derived(!sharedCopy && !!store && latest > 1) let pinnedContent = $state<ArtifactVersion | undefined>(undefined) // A pin that arrives with the tab has nothing honest to show until its snapshot lands: the @@ -58,6 +62,7 @@ return } const id = artifact.id + if (!store) return void store.getVersion(id, version).then( (snapshot) => { if (pinned !== version || artifact.id !== id) return @@ -132,7 +137,7 @@ {badge.label} </span> {/if} - {#if hasHistory} + {#if hasHistory && store} <!-- The body is blank while restoring, so the chip names the version being fetched: the latest is the one version certainly not on screen. --> <ArtifactVersionPicker @@ -146,14 +151,16 @@ <div class="flex items-center gap-2 shrink-0"> <!-- Both export and share `shown`, which is still the current document while a pin is restoring, so both wait for it. --> - <ArtifactShareButton - artifactId={artifact.id} - name={shown.name} - kind={artifact.kind} - content={shown.content} - version={shownVersion ?? latest} - disabled={restoringPin} - /> + {#if !sharedCopy} + <ArtifactShareButton + artifactId={artifact.id} + name={shown.name} + kind={artifact.kind} + content={shown.content} + version={shownVersion ?? latest} + disabled={restoringPin} + /> + {/if} <ArtifactExportButton name={shown.name} kind={artifact.kind} @@ -226,13 +233,19 @@ > <ClipboardList size={12} class="shrink-0" /> <span class="truncate"> - This revision is not approved · the plan you approved is v{view.backToPlan} + {#if sharedCopy} + This revision is not approved · the approved plan is v{view.backToPlan} + {:else} + This revision is not approved · the plan you approved is v{view.backToPlan} + {/if} </span> - <div class="ml-auto shrink-0"> - <Button unifiedSize="xs" variant="default" onClick={() => selectVersion(view.backToPlan)}> - View the plan - </Button> - </div> + {#if !sharedCopy} + <div class="ml-auto shrink-0"> + <Button unifiedSize="xs" variant="default" onClick={() => selectVersion(view.backToPlan)}> + View the plan + </Button> + </div> + {/if} </div> {/if} diff --git a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactsSegment.svelte b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactsSegment.svelte index b1a204346c..c9391a0f65 100644 --- a/frontend/src/lib/components/copilot/chat/artifacts/ArtifactsSegment.svelte +++ b/frontend/src/lib/components/copilot/chat/artifacts/ArtifactsSegment.svelte @@ -10,8 +10,15 @@ import { currentVersion, type PersistedArtifact } from './artifactsDB' import { planFirst } from './artifactsState.svelte' + let { + readOnly + }: { + /** A transcript nobody can change: its own artifacts, opened by the caller, none deleted. */ + readOnly?: { artifacts: PersistedArtifact[]; open: (artifact: PersistedArtifact) => void } + } = $props() + const aiChatManager = getAiChatManager() - const artifacts = $derived(aiChatManager.artifacts.artifacts) + const artifacts = $derived(readOnly?.artifacts ?? aiChatManager.artifacts.artifacts) // The plan is what the user comes back to, and in update order it sinks under // everything the approved run then produces. const planCount = $derived(artifacts.filter((a) => a.role === 'plan').length) @@ -33,7 +40,9 @@ itemKey={(a) => a.id} rowTitle={(a) => a.name} separatorAfter={(_, index) => index === planCount - 1 && planCount < orderedArtifacts.length} - onPick={(a: PersistedArtifact) => aiChatManager.openArtifact?.(a.id, a.name, listOpenTarget(a))} + onPick={(a: PersistedArtifact) => + readOnly ? readOnly.open(a) : aiChatManager.openArtifact?.(a.id, a.name, listOpenTarget(a))} + actions={readOnly ? undefined : deleteAction} > {#snippet row(a)} {@const Icon = rowIcon(a)} @@ -55,26 +64,30 @@ > {badge?.label ?? a.kind} </span> - <span - class="min-w-[4.5rem] shrink-0 text-right text-2xs font-normal text-hint" - title={displayDate(new Date(a.updatedAt))} - > - {#if currentVersion(a) > 1}<span class="tabular-nums">v{currentVersion(a)}</span> ·{/if} - <TimeAgo date={new Date(a.updatedAt).toISOString()} compact /> - </span> - {/snippet} - {#snippet actions(a)} - <Button - unifiedSize="xs" - destructive - variant="subtle" - iconOnly - title="Delete" - startIcon={{ icon: Trash2 }} - onClick={() => { - aiChatManager.closeArtifact?.(a.id) - void aiChatManager.artifacts.remove(a.id) - }} - /> + <!-- A share made before edit times were kept has none. --> + {#if a.updatedAt} + <span + class="min-w-[4.5rem] shrink-0 text-right text-2xs font-normal text-hint" + title={displayDate(new Date(a.updatedAt))} + > + {#if currentVersion(a) > 1}<span class="tabular-nums">v{currentVersion(a)}</span> ·{/if} + <TimeAgo date={new Date(a.updatedAt).toISOString()} compact /> + </span> + {/if} {/snippet} </SessionStatusPopover> + +{#snippet deleteAction(a: PersistedArtifact)} + <Button + unifiedSize="xs" + destructive + variant="subtle" + iconOnly + title="Delete" + startIcon={{ icon: Trash2 }} + onClick={() => { + aiChatManager.closeArtifact?.(a.id) + void aiChatManager.artifacts.remove(a.id) + }} + /> +{/snippet} diff --git a/frontend/src/lib/components/copilot/chat/artifacts/DisplayCodeBlock.svelte b/frontend/src/lib/components/copilot/chat/artifacts/DisplayCodeBlock.svelte new file mode 100644 index 0000000000..d9a0fc6fa3 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/artifacts/DisplayCodeBlock.svelte @@ -0,0 +1,7 @@ +<script lang="ts"> + import MarkdownCodeBlock from '$lib/components/MarkdownCodeBlock.svelte' +</script> + +<!-- A `pre` renderer for untrusted artifact markdown: ```wm-display fences render (the fence + admits only inert kinds), mermaid stays source. --> +<MarkdownCodeBlock renderDisplay /> diff --git a/frontend/src/lib/components/copilot/chat/artifacts/MermaidCodeBlock.svelte b/frontend/src/lib/components/copilot/chat/artifacts/MermaidCodeBlock.svelte index 76756ab5b0..c993831c80 100644 --- a/frontend/src/lib/components/copilot/chat/artifacts/MermaidCodeBlock.svelte +++ b/frontend/src/lib/components/copilot/chat/artifacts/MermaidCodeBlock.svelte @@ -2,5 +2,6 @@ import MarkdownCodeBlock from '$lib/components/MarkdownCodeBlock.svelte' </script> -<!-- A `pre` renderer for ArtifactBody: the shared code block, with ```mermaid fences drawn. --> -<MarkdownCodeBlock renderMermaid /> +<!-- A `pre` renderer for ArtifactBody: the shared code block, with ```mermaid fences drawn and + ```wm-display fences rendered. --> +<MarkdownCodeBlock renderMermaid renderDisplay /> diff --git a/frontend/src/lib/components/copilot/chat/artifacts/artifactDocument.css b/frontend/src/lib/components/copilot/chat/artifacts/artifactDocument.css new file mode 100644 index 0000000000..7e171aff6b --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/artifacts/artifactDocument.css @@ -0,0 +1,498 @@ +/* + * The artifact document look, shared by the in-app viewer, the shared page, the PDF download and + * the HTML export. Plain CSS rather than Tailwind because the HTML export inlines this file into a + * standalone page, where no Tailwind build exists. Colours come from the theme's `--color-*` + * tokens (rgb triplets); the HTML export defines the light ones itself (`artifactExport.ts`). + * Everything is scoped under `.wm-doc` and every tunable is a `--doc-*` variable, so a rule + * scoped the same way restyles it: /kitchen_sink/artifacts writes such rules live. + */ + +.wm-doc { + --doc-font-body: Inter, 'Noto Color Emoji', system-ui, sans-serif; + --doc-font-heading: var(--doc-font-body); + --doc-font-mono: + 'JetBrains Mono Variable', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + /* The body face's OpenType features. Inter's ss04 gives the I serifs and the l a tail, without + the slashed zero of ss02, and cv11 sets a single-storey a. */ + --doc-features: 'ss04', 'cv11'; + --doc-size: 15px; + --doc-leading: 1.7; + --doc-scale: 1.2; + --doc-heading-weight: 600; + /* The heading face's x-height as a share of its font size (`font-size-adjust`). */ + --doc-heading-adjust: 0.5; + /* About 93 characters of Inter, the middle of the 620 to 840px columns document tools set: + wider than a book's, for the tables and code these documents carry. Not `ch`: that is the + width of a zero, which in Inter is a third wider than the average letter. */ + --doc-measure: 46em; + + --doc-text: rgb(var(--color-text-primary)); + --doc-heading: rgb(var(--color-text-emphasis)); + --doc-muted: rgb(var(--color-text-secondary)); + --doc-accent: rgb(var(--color-text-accent)); + --doc-rule: rgb(var(--color-border-light)); + --doc-rule-strong: rgb(var(--color-border-normal)); + --doc-sunken: rgb(var(--color-surface-secondary)); + /* Every panel: code, tables, callouts, images. */ + --doc-radius: 0.6rem; + --doc-alert-note: rgb(9 105 218); + --doc-alert-tip: rgb(26 127 55); + --doc-alert-important: rgb(130 80 223); + --doc-alert-warning: rgb(154 103 0); + --doc-alert-caution: rgb(207 34 46); + --doc-alert-tint: 7%; + --doc-check: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M4 8.5l2.5 2.5L12 5.5' fill='none' stroke='%23fff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); + + max-width: var(--doc-measure); + color: var(--doc-text); + font-family: var(--doc-font-body); + font-size: var(--doc-size); + font-feature-settings: var(--doc-features); + line-height: var(--doc-leading); + overflow-wrap: break-word; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +:where(.dark) .wm-doc { + --doc-alert-note: rgb(88 166 255); + --doc-alert-tip: rgb(63 185 80); + --doc-alert-important: rgb(163 113 247); + --doc-alert-warning: rgb(210 153 34); + --doc-alert-caution: rgb(248 81 73); + --doc-alert-tint: 11%; + --doc-check: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='M4 8.5l2.5 2.5L12 5.5' fill='none' stroke='%231d2430' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); +} + +/* The panel or page around the document, which a table wider than the column can grow into. */ +.wm-doc-frame { + container-type: inline-size; +} + +/* `--doc-features` names the body face's features. Code, diagrams and section numbers are set in + other faces, which read the same tags as other glyphs, or as none. */ +.wm-doc :is(code, kbd, pre, svg), +.wm-doc h2::before { + font-feature-settings: normal; +} + +.wm-doc > :first-child { + margin-top: 0; +} +.wm-doc > :last-child { + margin-bottom: 0; +} +.wm-doc ::selection { + background: color-mix(in srgb, var(--doc-accent) 22%, transparent); +} + +/* Headings: h1 to h3 in the heading face on a modular scale, h4 to h6 as body-face labels. */ +.wm-doc :is(h1, h2, h3, h4, h5, h6) { + color: var(--doc-heading); + font-family: var(--doc-font-heading); + font-weight: var(--doc-heading-weight); + line-height: 1.25; + letter-spacing: -0.01em; + text-wrap: balance; +} +/* The heading face is sized by its x-height, so one with a smaller lowercase than the body's, as a + serif has, does not set h3 below the body text. Line heights still multiply the unadjusted + size, so h1 to h3 take larger ones to keep the same space between lines. */ +.wm-doc :is(h1, h2, h3, blockquote) { + font-size-adjust: var(--doc-heading-adjust); +} +.wm-doc :is(h1, h2, h3) { + line-height: 1.3; +} +.wm-doc h1 { + margin: 0 0 0.7em; + font-size: calc(var(--doc-size) * var(--doc-scale) * var(--doc-scale) * var(--doc-scale)); + line-height: 1.25; + letter-spacing: -0.02em; +} +.wm-doc h2 { + margin: 2.1em 0 0.55em; + font-size: calc(var(--doc-size) * var(--doc-scale) * var(--doc-scale)); +} +/* Each section opens with its number. `artifactPlugins` marks the headings of a document that + numbers its own sections, which take none; the footnotes' heading is visually hidden. */ +.wm-doc { + counter-reset: doc-section; +} +.wm-doc h2:not(.sr-only, .wm-unnumbered) { + counter-increment: doc-section; +} +.wm-doc h2:not(.sr-only, .wm-unnumbered)::before { + content: counter(doc-section, decimal-leading-zero); + display: inline-block; + margin-right: 0.75em; + vertical-align: 0.3em; + color: var(--doc-accent); + font-family: var(--doc-font-mono); + font-size: 0.55em; + font-weight: 500; + letter-spacing: 0.04em; +} +.wm-doc h3 { + margin: 1.8em 0 0.45em; + font-size: calc(var(--doc-size) * var(--doc-scale)); +} +.wm-doc :is(h4, h5, h6) { + margin: 1.6em 0 0.35em; + font-family: var(--doc-font-body); + font-size: 1em; + font-weight: 600; + letter-spacing: 0; +} +.wm-doc :is(h5, h6) { + color: var(--doc-muted); +} + +.wm-doc p { + margin: 0 0 1.1em; + text-wrap: pretty; +} +/* A diagram sizes each label's box to its text laid out as mermaid wraps it (one line unless + too long). `text-wrap` above would reset that, and a label that renders a hair wider than + measured would break onto a line its box hides. */ +.wm-doc svg p { + text-wrap: inherit; +} +.wm-doc strong { + color: var(--doc-heading); + font-weight: 600; +} +.wm-doc del { + color: var(--doc-muted); +} +.wm-doc sup { + font-size: 0.72em; + line-height: 0; +} + +.wm-doc a { + color: var(--doc-accent); + text-decoration: underline; + text-decoration-thickness: 1px; + text-decoration-color: color-mix(in srgb, currentColor 35%, transparent); + text-underline-offset: 0.22em; +} +.wm-doc a:hover { + text-decoration-color: currentColor; +} + +.wm-doc :is(ul, ol) { + margin: 0 0 1.1em; + padding-left: 1.4em; +} +.wm-doc ul { + list-style: disc; +} +.wm-doc ul ul { + list-style: circle; +} +.wm-doc ol { + list-style: decimal; +} +.wm-doc li { + margin: 0.3em 0; + padding-left: 0.2em; +} +.wm-doc li > :is(ul, ol) { + margin: 0.3em 0 0; +} +.wm-doc li > p { + margin: 0.4em 0; +} +.wm-doc ul > li::marker { + color: var(--doc-rule-strong); +} +.wm-doc ol > li::marker { + color: var(--doc-muted); + font-variant-numeric: tabular-nums; +} + +.wm-doc .contains-task-list { + padding-left: 0; + list-style: none; +} +.wm-doc .task-list-item { + position: relative; + padding-left: 1.7em; +} +.wm-doc .task-list-item:has(> input:checked) { + color: var(--doc-muted); +} +/* `:disabled` and `!important` are what outrank the app's global form styles, which give + every input a background; GFM checkboxes are always disabled. */ +.wm-doc .task-list-item > input[type='checkbox']:disabled { + appearance: none; + position: absolute; + top: calc(0.5lh - 0.45em); + left: 0; + display: block; + width: 0.9em; + height: 0.9em; + margin: 0; + padding: 0; + font-size: inherit; + line-height: inherit; + border: 1.5px solid var(--doc-rule-strong); + border-radius: 0.3em; + background-color: transparent !important; + background-image: none; +} +.wm-doc .task-list-item > input[type='checkbox']:checked:disabled { + border-color: var(--doc-accent); + background-color: var(--doc-accent) !important; + background-image: var(--doc-check); + background-position: center; + background-size: 100%; + background-repeat: no-repeat; +} + +/* Code reads character for character: no `=>` turning into an arrow in a font that ligates. A + quote's italic and x-height sizing are for its own face, not code inside it. */ +.wm-doc :is(code, kbd, pre) { + font-variant-ligatures: none; + font-style: normal; + font-size-adjust: none; +} +.wm-doc :not(pre) > code { + padding: 0.12em 0.4em; + border-radius: 0.35em; + background: var(--doc-sunken); + color: var(--doc-heading); + font-family: var(--doc-font-mono); + font-size: 0.86em; +} +.wm-doc kbd { + padding: 0.1em 0.45em; + border: 1px solid var(--doc-rule); + border-bottom-width: 2px; + border-radius: 0.35em; + font-family: var(--doc-font-mono); + font-size: 0.8em; +} + +/* In the app and the PDF, fenced code is the code-block renderer's own panel (`.not-prose`); in + the HTML export it is a plain `pre`, at any depth, since a list item or a quote can hold one. */ +.wm-doc > .not-prose { + margin: 1.5em 0; +} +.wm-doc > .not-prose > div { + border-radius: var(--doc-radius); +} +/* `!important`: the app's global `pre code.hljs` rule pins code to text-xs. */ +.wm-doc pre code.hljs { + font-family: var(--doc-font-mono); + font-size: calc(var(--doc-size) * 0.82) !important; + line-height: 1.6 !important; +} +.wm-doc pre:not(.not-prose pre) { + margin: 1.5em 0; + padding: 1em 1.2em; + overflow-x: auto; + border-radius: var(--doc-radius); + background: var(--doc-sunken); + font-family: var(--doc-font-mono); + font-size: 0.82em; + line-height: 1.6; + white-space: pre; +} +/* The browser's own `code { font-family: monospace }` would otherwise outrank the block's font. */ +.wm-doc pre:not(.not-prose pre) > code { + font: inherit; +} + +.wm-doc blockquote { + margin: 1.5em 0; + padding: 0.1em 0 0.1em 1.2em; + border-left: 2px solid color-mix(in srgb, var(--doc-rule-strong) 55%, transparent); + color: var(--doc-muted); + font-family: var(--doc-font-heading); + font-size: 1.05em; + font-style: italic; +} +.wm-doc blockquote > :last-child { + margin-bottom: 0; +} + +.wm-doc hr { + height: auto; + margin: 2.4em 0; + overflow: visible; + border: 0; + color: var(--doc-rule-strong); + text-align: center; +} +.wm-doc hr::after { + content: '\00B7\2003\00B7\2003\00B7'; + font-size: 1.1em; + line-height: 1; +} + +/* A rounded frame, rows separated by hairlines, the header row on the sunken surface. + `display: block` is what lets a wide table scroll inside its frame, and the scroll box is what + clips the header's corners to the radius. */ +.wm-doc table { + display: block; + width: max-content; + max-width: 100%; + margin: 1.5em 0; + overflow-x: auto; + border: 1px solid var(--doc-rule); + border-radius: var(--doc-radius); + border-collapse: collapse; + font-size: 0.9em; + font-variant-numeric: tabular-nums; + line-height: 1.5; +} +/* A table wider than the column grows to the right, up to the width of `.wm-doc-frame`, or of + the viewport where no frame holds the document (the PDF's print frame, as wide as the column). + Only a top-level table: one indented in a list or a quote would pass the frame's edge. */ +.wm-doc > table { + max-width: max(100%, 100cqi); +} +.wm-doc :is(th, td) { + padding: 0.6em 1em; + border-bottom: 1px solid var(--doc-rule); + text-align: left; + vertical-align: top; +} +.wm-doc th { + background: var(--doc-sunken); + color: var(--doc-muted); + font-weight: 600; + vertical-align: bottom; +} +.wm-doc tbody tr:last-child > td { + border-bottom: 0; +} +.wm-doc :is(th, td)[align='right'] { + text-align: right; +} +.wm-doc :is(th, td)[align='center'] { + text-align: center; +} +/* Cells as `artifactPlugins` marks them. A short one stays on one line and a long one wraps no + narrower than 12em, so a table too wide for the column scrolls instead of breaking every cell + at its narrowest. `content-box` because the app's reset makes it border-box and the HTML export + has no reset. */ +.wm-doc .wm-cell-short { + white-space: nowrap; +} +.wm-doc .wm-cell-long { + box-sizing: content-box; + min-width: 12em; +} + +.wm-doc img { + max-width: 100%; + height: auto; + border-radius: var(--doc-radius); +} + +/* The HTML export's diagrams, on the panel the app draws them on. */ +.wm-doc .wm-diagram { + display: flex; + justify-content: center; + margin: 1.5em 0; + padding: 0.5rem; + overflow-x: auto; + border-radius: var(--doc-radius); + background: var(--doc-sunken); +} + +.wm-doc details { + margin: 1.2em 0; +} +.wm-doc summary { + color: var(--doc-heading); + font-weight: 600; + cursor: pointer; +} +.wm-doc details[open] > summary { + margin-bottom: 0.6em; +} + +/* GFM callouts. `border: 0` and the doubled class keep the chat's own callout styles, which + are global once a chat message has rendered, from showing through. */ +.wm-doc .markdown-alert { + --alert: var(--doc-muted); + margin: 1.5em 0; + padding: 0.9em 1.15em; + border: 0; + border-radius: var(--doc-radius); + background: color-mix(in srgb, var(--alert) var(--doc-alert-tint), transparent); +} +.wm-doc .markdown-alert > :last-child { + margin-bottom: 0; +} +.wm-doc .markdown-alert .markdown-alert-title { + display: flex; + align-items: center; + gap: 0.5em; + margin: 0 0 0.4em; + color: var(--alert); + font-size: 0.9em; + font-weight: 600; + line-height: 1.4; +} +.wm-doc .markdown-alert .markdown-alert-title > svg { + flex: none; + width: 1.25em; + height: 1.25em; + margin: 0; + fill: currentColor; +} +.wm-doc .markdown-alert-note { + --alert: var(--doc-alert-note); +} +.wm-doc .markdown-alert-tip { + --alert: var(--doc-alert-tip); +} +.wm-doc .markdown-alert-important { + --alert: var(--doc-alert-important); +} +.wm-doc .markdown-alert-warning { + --alert: var(--doc-alert-warning); +} +.wm-doc .markdown-alert-caution { + --alert: var(--doc-alert-caution); +} + +.wm-doc .footnotes { + margin-top: 3em; + padding-top: 1.2em; + border-top: 1px solid var(--doc-rule); + color: var(--doc-muted); + font-size: 0.85em; +} +.wm-doc :is([data-footnote-ref], [data-footnote-backref]) { + text-decoration: none; +} +/* Tailwind's utility, restated for the export: GFM labels the footnotes with it. */ +.wm-doc .sr-only { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +@media print { + .wm-doc :is(h1, h2, h3, h4) { + break-after: avoid; + } + .wm-doc :is(pre, table, .markdown-alert, img, .wm-diagram) { + break-inside: avoid; + } + .wm-doc pre:not(.not-prose pre) { + white-space: pre-wrap; + } +} diff --git a/frontend/src/lib/components/copilot/chat/artifacts/artifactExport.test.ts b/frontend/src/lib/components/copilot/chat/artifacts/artifactExport.test.ts new file mode 100644 index 0000000000..8b02410c05 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/artifacts/artifactExport.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it, vi } from 'vitest' +import { artifactHtmlDocument, renderArtifactHtml } from './artifactExport' + +// The export never mounts the fenced-code renderer: keep its component tree out of the test. +vi.mock('$lib/components/MarkdownCodeBlock.svelte', () => ({ default: {} })) + +describe('artifact HTML export', () => { + it('keeps the content but drops scripts, handlers and javascript: links', () => { + const html = renderArtifactHtml( + [ + '<script>alert(1)</script>', + '<img src="x.png" onerror="alert(2)">', + '[link](javascript:alert(3))', + '<a href="https://windmill.dev" onclick="alert(4)">site</a>' + ].join('\n\n') + ) + expect(html).not.toMatch(/<script|onerror|onclick|javascript:/i) + expect(html).toContain('<img src="x.png">') + expect(html).toContain('<a href="https://windmill.dev">site</a>') + }) + + it('marks table cells after the sanitize stage, which would strip the classes', () => { + const html = renderArtifactHtml(`| a | ${'long '.repeat(6)}|\n| - | - |\n| b | c |`) + expect(html).toContain('<th class="wm-cell-short">a</th>') + expect(html).toContain('<th class="wm-cell-long">') + expect(html).toContain('<td class="wm-cell-short">c</td>') + }) + + it('leaves the section numbers to a document whose headings carry their own', () => { + for (const heading of ['19th century', '2024', '1.5 release', '1,000 users']) { + expect(renderArtifactHtml(`## Gaul\n\n## ${heading}`)).not.toContain('wm-unnumbered') + } + for (const heading of ['1. Goals', '1 Goals', '1️⃣ Goals']) { + expect(renderArtifactHtml(`## Summary\n\n## ${heading}`)).toContain( + '<h2 class="wm-unnumbered">Summary</h2>' + ) + } + }) + + it('escapes the name it writes into the page title', () => { + const page = artifactHtmlDocument('', '# Hi') + expect(page).toContain('</title><script>alert(1)</script>') + expect(page).not.toMatch(/ + + -{#if showSvg} -
+{#if showSource} +
{code}
+{:else if svg === undefined} + +
+ +
+{:else} +
-{:else} - -
{code}
{/if} diff --git a/frontend/src/lib/components/copilot/chat/script/core.ts b/frontend/src/lib/components/copilot/chat/script/core.ts index e7053ce141..79f8621e40 100644 --- a/frontend/src/lib/components/copilot/chat/script/core.ts +++ b/frontend/src/lib/components/copilot/chat/script/core.ts @@ -26,7 +26,7 @@ import { createWorkspaceMutationTools } from '../workspaceTools' import { setupTypeAcquisition, type DepsToGet } from '$lib/ata' import { getEffectiveModelContextWindow } from '../../modelConfig' import type { ReviewChangesOpts } from '../monaco-adapter' -import { copilotInfo, getCurrentModel } from '$lib/aiStore' +import { copilotInfo, getCurrentModel, type SessionAi } from '$lib/aiStore' import { get } from 'svelte/store' import { getDbSchemas } from '$lib/components/apps/components/display/dbtable/metadata' import { scriptLangToEditorLang } from '$lib/scripts' @@ -604,7 +604,10 @@ type PackageSearchResult = { } const packagesSearchCache = new Map() -export async function searchExternalIntegrationResources(args: { query: string }): Promise { +export async function searchExternalIntegrationResources( + args: { query: string }, + sessionAi?: SessionAi +): Promise { try { if (packagesSearchCache.has(args.query)) { return JSON.stringify(packagesSearchCache.get(args.query)) @@ -619,11 +622,14 @@ export async function searchExternalIntegrationResources(args: { query: string } (r: PackageSearchQuery) => r.searchScore >= best * NPM_RUNNER_UP_SHARE ) - const model = getCurrentModel() + const model = sessionAi ? sessionAi.model : getCurrentModel() + if (!model) { + throw new Error('No model selected') + } const modelContextWindow = getEffectiveModelContextWindow( model.provider, model.model, - get(copilotInfo).contextWindowPerModel + (sessionAi ? sessionAi.info : get(copilotInfo))?.contextWindowPerModel ) const results: PackageSearchResult[] = await Promise.all( filtered.map(async (r: PackageSearchQuery) => { @@ -684,9 +690,10 @@ export const searchNpmPackagesTool: SessionTool<{}> = { requires: NONE, def: SEARCH_NPM_PACKAGES_TOOL, planModeSafe: true, - fn: async ({ args, toolId, toolCallbacks }) => { + fn: async ({ args, toolId, toolCallbacks, helpers }) => { toolCallbacks.setToolStatus(toolId, { content: 'Searching for relevant packages...' }) - const result = await searchExternalIntegrationResources(args) + const sessionAi = (helpers as { sessionAi?: () => SessionAi } | undefined)?.sessionAi + const result = await searchExternalIntegrationResources(args, sessionAi?.()) toolCallbacks.setToolStatus(toolId, { content: 'Retrieved relevant packages' }) return result } diff --git a/frontend/src/lib/components/copilot/chat/script/mermaidConfig.ts b/frontend/src/lib/components/copilot/chat/script/mermaidConfig.ts new file mode 100644 index 0000000000..af623886d4 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/script/mermaidConfig.ts @@ -0,0 +1,19 @@ +import type { MermaidConfig } from 'mermaid' + +/** The settings every diagram is drawn with, in the app and in an artifact's HTML download. */ +export function mermaidConfig(dark: boolean): MermaidConfig { + return { + startOnLoad: false, + theme: dark ? 'dark' : 'default', + securityLevel: 'strict', + // Mermaid writes this stack into a diff --git a/frontend/src/lib/components/sessions/SharedSessionBody.svelte b/frontend/src/lib/components/sessions/SharedSessionBody.svelte new file mode 100644 index 0000000000..cebf4cfd72 --- /dev/null +++ b/frontend/src/lib/components/sessions/SharedSessionBody.svelte @@ -0,0 +1,115 @@ + + +{#snippet sharedBy()} + {#if loaded?.state === 'found'} +
+ Read-only {loaded.session.is_public ? 'public ' : ''}copy shared by {loaded.session + .created_by} + · {displayDate(loaded.session.shared_at)} +
+ {/if} +{/snippet} + +{#if loaded?.state === 'found' && loaded.snapshot.messages.length > 0} + {#key loaded.session.id} + + {/key} +{:else} +
+
+ {@render placeholder()} +
+
+{/if} + +{#snippet placeholder()} + {#if loaded?.state === 'found'} + + {@render sharedBy()} + {:else if loaded?.state === 'gone'} + + {:else if loaded?.state === 'outsider'} + + {:else if loaded?.state === 'error'} + + {:else} +
+ +
+ {/if} +{/snippet} diff --git a/frontend/src/lib/components/sessions/SharedSessionPreview.svelte b/frontend/src/lib/components/sessions/SharedSessionPreview.svelte new file mode 100644 index 0000000000..bfcdfe8ac8 --- /dev/null +++ b/frontend/src/lib/components/sessions/SharedSessionPreview.svelte @@ -0,0 +1,72 @@ + + + +
+
+ + {#if actions} +
+ {@render actions()} +
+ {/if} +
+ onReorder(order.map((t) => t.id))} + class="session-preview-tab-strip h-8 border-b border-light bg-surface-secondary/50 pl-9 pr-[var(--preview-actions-w)]" + /> +
+ +
+ {#each tabs as artifact (artifact.id)} +
+ {}} /> +
+ {/each} +
+
+
diff --git a/frontend/src/lib/components/sessions/SharedSessionStatusBar.svelte b/frontend/src/lib/components/sessions/SharedSessionStatusBar.svelte new file mode 100644 index 0000000000..0e86b6b183 --- /dev/null +++ b/frontend/src/lib/components/sessions/SharedSessionStatusBar.svelte @@ -0,0 +1,193 @@ + + + + +{#snippet lockedNote()} +
+ + + {draftsLockedReason} + {#if draftsSignInHref} + Sign in + {/if} + +
+{/snippet} + +{#if edits.length > 0 || artifacts.length > 0} +
+ {#if edits.length > 0} + `${e.kind}:${e.path}`} + itemHref={deployedHref} + {rowTitle} + itemDisabled={(edit) => (edit.draft ? !opensDraft(edit) : !deployedHref(edit))} + onPick={(edit) => void viewDraft(edit)} + triggerClass={`${TOKEN_TRIGGER_CLASS} ${token.class}`} + widthClass="w-96" + maxHeightClass="max-h-[min(9rem,50vh)]" + footer={draftsLockedReason && hasLockedRow ? lockedNote : undefined} + > + {#snippet row(edit)} + + + {edit.path} + + {#if edit.draft} + {edit.draftOnly ? 'Draft only' : 'Draft'} + {#if opensDraft(edit)} + + {:else} + + {/if} + {:else} + Deployed + {#if deployedHref(edit)} + + {/if} + {/if} + {/snippet} + + {/if} + {#if artifacts.length > 0} + + {/if} +
+{/if} + +{#if diffDrawerModule.current} + {@const LoadedDiffDrawer = diffDrawerModule.current.default} + +{/if} diff --git a/frontend/src/lib/components/sessions/SharedSessionTitle.svelte b/frontend/src/lib/components/sessions/SharedSessionTitle.svelte new file mode 100644 index 0000000000..1d4eb19a9f --- /dev/null +++ b/frontend/src/lib/components/sessions/SharedSessionTitle.svelte @@ -0,0 +1,52 @@ + + + +{name} +{#if author} + + + + + + {userInitials(author)} + + + {#snippet text()} +
+ Shared by {author} + {#if sharedAt} + {displayDate(sharedAt)} + {/if} +
+ {/snippet} +
+{/if} +{#if isPublic} + + +{/if} diff --git a/frontend/src/lib/components/sessions/SharedSessionTranscript.svelte b/frontend/src/lib/components/sessions/SharedSessionTranscript.svelte index 19239fe48c..52934afd52 100644 --- a/frontend/src/lib/components/sessions/SharedSessionTranscript.svelte +++ b/frontend/src/lib/components/sessions/SharedSessionTranscript.svelte @@ -1,10 +1,17 @@ diff --git a/frontend/src/lib/components/settings/CreateToken.svelte b/frontend/src/lib/components/settings/CreateToken.svelte index 20b97d9b87..41799824f8 100644 --- a/frontend/src/lib/components/settings/CreateToken.svelte +++ b/frontend/src/lib/components/settings/CreateToken.svelte @@ -332,6 +332,9 @@ {/if} w.id) + : mcpWorkspaces} bind:scopes={mcpScopes} bind:access={() => mcpAccess, setMcpAccess} > diff --git a/frontend/src/lib/components/settings/EditTokenScopesModal.svelte b/frontend/src/lib/components/settings/EditTokenScopesModal.svelte index 8ca8e2cdb7..0847724740 100644 --- a/frontend/src/lib/components/settings/EditTokenScopesModal.svelte +++ b/frontend/src/lib/components/settings/EditTokenScopesModal.svelte @@ -6,8 +6,13 @@ import Modal from '../common/modal/Modal.svelte' import TextInput from '../text_input/TextInput.svelte' import ScopesPicker from './ScopesPicker.svelte' - import McpAccessPicker, { MCP_SESSION, mcpAccessOf } from '../mcp/McpAccessPicker.svelte' + import McpAccessPicker, { + MCP_SESSION, + RUNNABLES_AS_TOOLS, + mcpAccessOf + } from '../mcp/McpAccessPicker.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { usersWorkspaceStore } from '$lib/stores' const operatingWorkspace = useOperatingWorkspace() @@ -39,6 +44,14 @@ (initialScopes ?? []).length > 0 && (initialScopes ?? []).every((s) => s.startsWith('mcp:')) ) const mcpWorkspaceId = $derived(tokenWorkspaceId ?? $operatingWorkspace ?? '') + // The workspaces the token reaches: its own, its list, or every one its owner is in. + const mcpReached = $derived.by(() => { + if (tokenWorkspaceId) return [tokenWorkspaceId] + const list = (initialScopes ?? []).find((s) => s.startsWith('mcp:workspaces:')) + return list + ? list.slice('mcp:workspaces:'.length).split(',') + : ($usersWorkspaceStore?.workspaces ?? []).map((w) => w.id) + }) let labelValue = $state('') let pickedScopes = $state(null) @@ -54,6 +67,13 @@ const access = mcpAccessOf(mcpScopes) return mcpTouched && (access === 'selected' || access !== mcpAccessOf(initialScopes ?? [])) }) + // An unedited older token (a plain `mcp:all` or an endpoint selection) keeps the endpoint tools + // on the per-workspace URLs, which the picker's levels do not describe, so it gets no warning. + const describedByPicker = (s: string) => + [MCP_SESSION, RUNNABLES_AS_TOOLS, 'mcp:read_only', 'mcp:read_run'].includes(s) + const warnsFor = $derived( + mcpEdited || (initialScopes ?? []).some(describedByPicker) ? mcpReached : [] + ) // Carried over as is, the picker knowing nothing of them: dropping the workspace list // would widen the token to every workspace, dropping `mcp:session` would move a sign-in // back to the endpoint tools once it is given `mcp:all` again. @@ -157,6 +177,7 @@ > !isWorkspaceList(s))} bind:scopes={mcpScopes} /> diff --git a/frontend/src/lib/components/settings/Trashbin.svelte b/frontend/src/lib/components/settings/Trashbin.svelte index ce45e7a7e2..fd71d83a76 100644 --- a/frontend/src/lib/components/settings/Trashbin.svelte +++ b/frontend/src/lib/components/settings/Trashbin.svelte @@ -7,6 +7,7 @@ import Row from '$lib/components/table/Row.svelte' import { workspaceStore } from '$lib/stores' import { sendUserToast } from '$lib/toast' + import { apiErrorMessage } from '$lib/utils' import { type TrashItem, TrashService } from '$lib/gen' import { Trash2, @@ -98,7 +99,7 @@ sendUserToast(`Restored ${getKindLabel(item.item_kind)} '${item.item_path}'`) loadItems() } catch (e) { - sendUserToast(`Failed to restore: ${e}`, true) + sendUserToast(`Failed to restore: ${apiErrorMessage(e)}`, true) } } @@ -111,7 +112,7 @@ sendUserToast(`Permanently deleted '${item.item_path}'`) loadItems() } catch (e) { - sendUserToast(`Failed to delete: ${e}`, true) + sendUserToast(`Failed to delete: ${apiErrorMessage(e)}`, true) } } @@ -121,7 +122,7 @@ sendUserToast(result) loadItems() } catch (e) { - sendUserToast(`Failed to empty trash: ${e}`, true) + sendUserToast(`Failed to empty trash: ${apiErrorMessage(e)}`, true) } } diff --git a/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte b/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte index da641a73a7..328224128c 100644 --- a/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte +++ b/frontend/src/lib/components/settings/WorkspaceUserSettings.svelte @@ -618,9 +618,11 @@
{#snippet action()} -
- - +
+
+ + +
{#if !isAdminsWorkspaceWithoutEE} {/snippet} {#snippet content()} -
+
Who joins without an invite
@@ -908,7 +910,7 @@ {/snippet} 30} + shouldLoadMore={(filteredUsers?.length ?? 0) > nbDisplayed} loadMore={30} on:loadMore={() => { nbDisplayed += 30 diff --git a/frontend/src/lib/components/sidebar/AiChatsSection.svelte b/frontend/src/lib/components/sidebar/AiChatsSection.svelte index 662174f7ae..398771e44f 100644 --- a/frontend/src/lib/components/sidebar/AiChatsSection.svelte +++ b/frontend/src/lib/components/sidebar/AiChatsSection.svelte @@ -11,6 +11,7 @@ import { useLocalStorageValue } from '$lib/svelte5Utils.svelte' import { agentOfChatPath } from '$lib/components/flows/conversations/agentEditorChat' import { sidebarClasses } from './MenuButton.svelte' + import SidebarShowOlder, { SIDEBAR_RECENT_MS } from './SidebarShowOlder.svelte' // The reader's own flow and agent chats, the ones a flow's or an agent's own page shows: the // editors' test chats stay with the editors. @@ -22,6 +23,8 @@ 'boolean' ) + const showOlder = useLocalStorageValue('windmill_ai_chats_show_older', false, 'boolean') + // Tagged with its workspace: responses are not ordered, and a late one from the workspace // just left must not show here. const listing = resource( @@ -34,7 +37,11 @@ kind: 'deployed', mine: true }) - return { ws, rows } + // Listed newest `updated_at` first, which every new message bumps, so the chats active + // in the window are a prefix of the page. + const since = Date.now() - SIDEBAR_RECENT_MS + const recent = rows.findIndex((c) => new Date(c.updated_at).getTime() < since) + return { ws, rows, recent: recent === -1 ? rows.length : recent } } ) // A chat is started on its flow's or agent's page, so it lists once the reader leaves one. @@ -43,8 +50,19 @@ if (!left || left === to?.url.pathname) return if (left.startsWith('/flows/get/') || left.startsWith('/agents/get/')) listing.refetch() }) + const current = $derived( + listing.current && listing.current.ws === $workspaceStore ? listing.current : undefined + ) + const allRows = $derived(current?.rows ?? []) + const openId = $derived(page.url.searchParams.get('conversation')) + // The open chat always lists, however old. const rows = $derived( - listing.current && listing.current.ws === $workspaceStore ? listing.current.rows : [] + showOlder.val || !current + ? allRows + : allRows.filter((c, i) => i < current.recent || c.id === openId) + ) + const olderCount = $derived( + allRows.filter((c, i) => i >= (current?.recent ?? 0) && c.id !== openId).length ) function target(c: FlowConversation) { @@ -55,11 +73,9 @@ href: `/${agent !== undefined ? 'agents' : 'flows'}/get/${agent ?? c.flow_path}?conversation=${c.id}` } } - - const openId = $derived(page.url.searchParams.get('conversation')) -{#if rows.length > 0} +{#if allRows.length > 0} {#if t.agent} - + + {:else} - + {/if} {c.title || 'Untitled chat'} {/each} + {#if olderCount > 0} + (showOlder.val = !showOlder.val)} + {rail} + /> + {/if}
{/snippet} diff --git a/frontend/src/lib/components/sidebar/SidebarSection.svelte b/frontend/src/lib/components/sidebar/SidebarSection.svelte index e19e9108ca..4e997f9ec8 100644 --- a/frontend/src/lib/components/sidebar/SidebarSection.svelte +++ b/frontend/src/lib/components/sidebar/SidebarSection.svelte @@ -29,6 +29,9 @@ A fold is a layout the reader keeps, so reaching a folded section's items never import Menu from '$lib/components/meltComponents/Menu.svelte' import MeltButton from '$lib/components/meltComponents/MeltButton.svelte' import { sidebarClasses } from './MenuButton.svelte' + import SessionStatusDot from '$lib/components/sessions/SessionStatusDot.svelte' + import type { SessionChatStatus } from '$lib/components/sessions/sessionRuntimeRegistry.svelte' + import UnreadCountBadge from '$lib/components/common/badge/UnreadCountBadge.svelte' interface Props { title: string @@ -38,6 +41,12 @@ A fold is a layout the reader keeps, so reaching a folded section's items never isCollapsed: boolean /** A dot on the icon: something inside wants attention. */ notify?: boolean + /** How many unread messages `notify` stands for: shown as a count instead of the dot, + * beside the title in the open sidebar and in the icon's place in the rail. */ + unreadCount?: number + /** A live session status the folded section shows for the items it hides, in place of + * the unread mark. */ + status?: SessionChatStatus /** A section with nothing to fold: the row stays, without its chevron. */ disabled?: boolean /** @@ -61,6 +70,8 @@ A fold is a layout the reader keeps, so reaching a folded section's items never onToggle, isCollapsed, notify = false, + unreadCount = 0, + status, disabled = false, actions, // Renamed: the menu's own `children` snippets below would shadow it. @@ -69,6 +80,7 @@ A fold is a layout the reader keeps, so reaching a folded section's items never }: Props = $props() const isFolded = $derived(folded && !disabled) + const showStatus = $derived(!!status && isFolded) const toggleLabel = $derived(isFolded ? `Unfold ${title}` : `Fold ${title}`) const rowClass = 'relative flex items-center justify-start w-full h-[30px] px-2 gap-2 rounded-lg text-left font-normal' @@ -99,9 +111,18 @@ A fold is a layout the reader keeps, so reaching a folded section's items never {#snippet sectionIcon()} - - {#if notify} - {@render notifyDot('absolute -top-1 -right-1')} + {#if showStatus && status} + + + + + {:else if notify && unreadCount > 0} + + {:else} + + {#if notify} + {@render notifyDot('absolute -top-1 -right-1')} + {/if} {/if} {/snippet} @@ -243,8 +264,14 @@ A fold is a layout the reader keeps, so reaching a folded section's items never {title} - {#if notify && (isFolded || disabled)} - {@render notifyDot('flex-shrink-0')} + {#if showStatus && status} + + {:else if notify && (isFolded || disabled)} + {#if unreadCount > 0} + + {:else} + {@render notifyDot('flex-shrink-0')} + {/if} {/if} {/if} diff --git a/frontend/src/lib/components/sidebar/SidebarShowOlder.svelte b/frontend/src/lib/components/sidebar/SidebarShowOlder.svelte new file mode 100644 index 0000000000..2d9bac8f19 --- /dev/null +++ b/frontend/src/lib/components/sidebar/SidebarShowOlder.svelte @@ -0,0 +1,36 @@ + + + + + + diff --git a/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte b/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte index 6da76342a2..2bd1b9548d 100644 --- a/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte +++ b/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte @@ -73,6 +73,9 @@ * families rather than within one — a session's, where the fork is the session's own and * not something the picker should offer to change. */ collapseFamilies?: boolean + /** Offered each pick before the switch; true means the host took it and nothing switches. + * A host that goes on to switch lands on home when `landOnHome` is set, as this picker would. */ + interceptSwitch?: (id: string, landOnHome: boolean) => boolean } let { @@ -80,10 +83,14 @@ strictWorkspaceSelect = false, keepPageOnSwitch = false, collapseFamilies = false, + interceptSwitch, closeMenu }: Props = $props() async function toggleSwitchWorkspace(id: string) { + if (interceptSwitch?.(id, landsOnHome(id))) { + return + } if ($workspaceStore === id) { return } @@ -123,6 +130,18 @@ }) } + // In the capture phase: the row's portaled link reaches SvelteKit's router, which navigates + // and so switches workspace, before the row's own click handler runs. + function offerPickToHost(e: MouseEvent, workspace: { id: string; disabled?: boolean }) { + if (workspace.disabled || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return + if (!(e.target as Element).closest('[role="menuitem"]')) return + if (interceptSwitch?.(workspace.id, landsOnHome(workspace.id))) { + e.preventDefault() + e.stopPropagation() + closeMenu?.() + } + } + function onWorkspaceItemClick(e: MouseEvent, workspace: { id: string; disabled?: boolean }) { if (workspace.disabled) { e.preventDefault() @@ -502,6 +521,7 @@
offerPickToHost(e, workspace)} class={twMerge( 'group flex items-center min-w-0 w-full', workspace.disabled diff --git a/frontend/src/lib/components/triggers/CaptureTable.svelte b/frontend/src/lib/components/triggers/CaptureTable.svelte index 88c2bfc3af..f7fe8f5f5f 100644 --- a/frontend/src/lib/components/triggers/CaptureTable.svelte +++ b/frontend/src/lib/components/triggers/CaptureTable.svelte @@ -1,4 +1,5 @@ - +
- + w.value) + : pickedWorkspaces + : [workspaceId]} initialScopes={requestedScopes} bind:scopes bind:access={() => access, setAccess} diff --git a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte index a6a4dc761b..207f0a65fe 100644 --- a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte @@ -1,1493 +1,28 @@ - - - - { - if (document.visibilityState === 'hidden') owner?.flushNow() - }} -/> - - - - - -{#snippet fullscreenBand()} - -
- {@render previewTabStrip(true)} -
-
- {@render previewControls()} -
+{#if embedded} +
+

Sessions can't open inside a preview

+

This page is being previewed in a session panel. Open it at the top level instead.

+
-{/snippet} - -{#snippet sessionPageActions()} - {#if previewCollapsed && !fullscreen} - - - - - {/if} -{/snippet} - -
- {#if embedded} - -
-

Sessions can't open inside a preview

-

This page is being previewed in a session panel. Open it at the top level instead.

- -
- {:else if !sessionState.hydrated} - -
- -
- {:else if !requestsSession || !activeSession || leaving} - -
- -
- {:else} - -
- -
- - - - - - -
- {#each mountedChatSessions as s (s.id)} -
- - tabNameFor(tab, getEffectiveWorkspaceId(s) ?? $workspaceStore ?? '')} - /> -
- {/each} -
-
- - - - -
previewWidth, - (w) => { - previewWidth = w - if (!fullscreen && !panesAnimating && contentWidth > 0) - panelShare = w / contentWidth - } - } - class="flex-1 min-h-0 flex flex-col {bandFullscreen - ? `p-0 ${BAR_TOP_PAD}` - : fullscreen - ? `px-2 pb-2 ${BAR_TOP_PAD}` - : 'p-2 pl-0'}" - > - -
- {#if !bandFullscreen} - - - {/if} - - - {#if !bandFullscreen} - -
- {@render previewControls()} -
- - {@render previewTabStrip(false)} - {/if} - - -
- {#if previewTabHostComponent.current} - {@const TabHost = previewTabHostComponent.current} - {#each warmHosts as { session: s, runtime: rt } (s.id)} - {@const tabs = rt.previewTabs} - {#each tabs?.tabs ?? [] as tab (tab.id)} - - - tabs && onTabLoad(tabs, tab, frame)} - /> - {/each} - {/each} - {/if} - {#if (owner?.tabs.length ?? 0) === 0} - -
- -
- No preview open - Open a page, flow, script or app to preview it alongside the chat. -
- - {#snippet trigger()} - - Open a preview - - {/snippet} - {#snippet content()} - { - emptyStateNewTabOpen = false - openInNewTab(t) - }} - /> - {/snippet} - -
- {/if} -
-
-
-
-
-
- {#if firstVerdictPending} -
- -
- {:else if aiHiddenVerdict} - - -
-

AI Sessions are hidden in this workspace

-

A workspace admin hid AI sessions in the workspace settings.

- -
- {/if} -
- {/if} -
- - -{#snippet previewControls()} - {#if activeWorkspaceHref} - - - - {/if} - {#if narrowScreen.current} - - {:else if fullscreen} - - - {:else} - - {/if} -{/snippet} - -{#snippet previewTabStrip(inBand: boolean)} - -
- (activeTabPickerOpen = !activeTabPickerOpen)} - onClose={closeTab} - onReorder={reorderTabs} - size={inBand ? 'md' : 'sm'} - class={inBand - ? 'session-preview-tab-strip h-full bg-transparent min-w-0' - : 'session-preview-tab-strip h-8 border-b border-light bg-surface-secondary/50 pl-9 pr-[var(--preview-actions-w,4rem)]'} - > - {#snippet tabAccessory(_tab, isActive)} - {#if isActive} - - - (e.currentTarget as HTMLElement).closest('[role="tab"]')?.focus() - }} - > - {#snippet content()} - - {#key activePickerScope?.dir ?? ''} - { - activeTabPickerOpen = false - navigatePreviewTo(t) - }} - /> - {/key} - {/snippet} - - - {/if} - {/snippet} - {#snippet afterTabs()} - - {#snippet trigger()} - - {/snippet} - {#snippet content()} - { - newTabOpen = false - openInNewTab(t) - }} - /> - {/snippet} - - {/snippet} - -
-{/snippet} - - +{/if} diff --git a/frontend/src/routes/(root)/(logged)/sessions/shared/[id]/+page.svelte b/frontend/src/routes/(root)/(logged)/sessions/shared/[id]/+page.svelte new file mode 100644 index 0000000000..47d5906883 --- /dev/null +++ b/frontend/src/routes/(root)/(logged)/sessions/shared/[id]/+page.svelte @@ -0,0 +1,111 @@ + + +{#snippet sessionName()} + +{/snippet} + +{#snippet headerActions()} + {#if found?.session.mine} + + {:else if found && isMember} +
+ + + {#if found.session.can_unshare} + shared.stopSharing() + } + ]} + > + {#snippet buttonReplacement()} + + + + {/snippet} + + {/if} +
+ {/if} +{/snippet} + + + +
+ +
diff --git a/frontend/src/routes/(root)/(logged)/shared_artifacts/[id]/+page.svelte b/frontend/src/routes/(root)/(logged)/shared_artifacts/[id]/+page.svelte index ac0d3cac02..3c5a8d2fc3 100644 --- a/frontend/src/routes/(root)/(logged)/shared_artifacts/[id]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/shared_artifacts/[id]/+page.svelte @@ -166,8 +166,9 @@ {#if artifact}
-
+ only while its parent box lasts, so that box must grow with the text. No width cap for + the document either: it sets its own column, and a wide table grows past it. --> +
diff --git a/frontend/src/routes/(root)/(logged)/workers/+page.svelte b/frontend/src/routes/(root)/(logged)/workers/+page.svelte index 71c069fe42..453a83daef 100644 --- a/frontend/src/routes/(root)/(logged)/workers/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/workers/+page.svelte @@ -50,7 +50,7 @@ import YAML from 'yaml' import { cleanWorkerGroupConfig } from '$lib/components/worker_group' - import { DEFAULT_TAGS_WORKSPACES_SETTING } from '$lib/consts' + import { DEFAULT_TAGS_WORKSPACES_SETTING, WORKSPACE_FAIRNESS_ENABLED_SETTING } from '$lib/consts' import AutoscalingEvents from '$lib/components/AutoscalingEvents.svelte' import HttpAgentWorkerDrawer from '$lib/components/HttpAgentWorkerDrawer.svelte' import WorkerRepl from '$lib/components/WorkerRepl.svelte' @@ -575,10 +575,24 @@ let newGroupPopover: Popover | undefined = $state(undefined) + let workspaceFairnessEnabled: boolean | undefined = $state(undefined) + async function loadWorkspaceFairnessEnabled() { + try { + workspaceFairnessEnabled = + (await SettingService.getGlobal({ key: WORKSPACE_FAIRNESS_ENABLED_SETTING })) === true + } catch (err) { + console.error('Failed to load the workspace fairness setting:', err) + } + } + $effect(() => { ;($superadmin || $devopsRole) && untrack(() => loadDefaultTagsPerWorkspace()) }) + $effect(() => { + ;($superadmin || $devopsRole) && untrack(() => loadWorkspaceFairnessEnabled()) + }) + $effect(() => { groupedWorkers && selectedTab == 'default' && @@ -975,6 +989,7 @@ }} activeWorkers={activeWorkers?.length ?? 0} {defaultTagPerWorkspace} + {workspaceFairnessEnabled} {width} shouldAutoOpenDrawer={shouldAutoOpenDrawer === worker_group[0]} onDrawerOpened={() => { @@ -1360,6 +1375,7 @@ name={worker_group[0]} config={worker_group[1]} activeWorkers={0} + {workspaceFairnessEnabled} {width} shouldAutoOpenDrawer={shouldAutoOpenDrawer === worker_group[0]} onDrawerOpened={() => { diff --git a/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte b/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte index 967823ee70..2c03b86f48 100644 --- a/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte @@ -29,7 +29,10 @@ import ForkMemberSettings from '$lib/components/settings/ForkMemberSettings.svelte' import SettingsPageHeader from '$lib/components/settings/SettingsPageHeader.svelte' import MemberWorkspaceSettings from '$lib/components/settings/MemberWorkspaceSettings.svelte' - import { WORKSPACE_SHOW_SLACK_CMD, WORKSPACE_SHOW_WEBHOOK_CLI_SYNC } from '$lib/consts' + import { + WORKSPACE_SETTINGS_SECTION_GROUPS, + workspaceSettingsSectionId + } from '$lib/components/workspaceSettings/workspaceSettingsSections' import { OauthService, SlackAgentsService, @@ -58,9 +61,13 @@ import { sendUserToast } from '$lib/toast' import { clone, emptyString, encodeState, hasUnsavedChanges } from '$lib/utils' import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile' - import { ExternalLink, Slack, Target } from 'lucide-svelte' + import { ArrowLeft, ExternalLink, Slack, Target } from 'lucide-svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' - import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' + import { + pageHeader, + type PageHeaderSection, + type PageHeaderSubpage + } from '$lib/components/pageHeaderRegistry.svelte' import SidebarNavigation from '$lib/components/common/sidebar/SidebarNavigation.svelte' import PremiumInfo from '$lib/components/settings/PremiumInfo.svelte' @@ -594,19 +601,12 @@ | 'dependencies' | 'rulesets' | 'shared_ui' - // Both 'slack' and 'teams' URLs map to 'slack' tab - if (selectedTab === 'teams') { - return 'slack' - } - // Both 'success_handler' and 'error_handler' URLs map to 'error_handler' tab - if (selectedTab === 'success_handler') { - return 'error_handler' - } - // The Deployment UI tab was folded into Dev workspace; keep its links working. - if (selectedTab === 'deploy_to') { - return 'dev_workspace' - } - return selectedTab || 'users' + return selectedTab + ? (workspaceSettingsSectionId(selectedTab) as Exclude< + typeof selectedTab, + 'teams' | 'success_handler' | 'deploy_to' + >) + : 'users' }) let slack_tabs: 'slack_commands' | 'teams_commands' = $derived( @@ -919,7 +919,7 @@ if (settings.deploy_ui != undefined && settings.deploy_ui != null) { deployUiSettings = { include_path: - (settings.deploy_ui.include_path?.length ?? 0 > 0) + (settings.deploy_ui.include_path?.length ?? 0) > 0 ? (settings.deploy_ui.include_path ?? []) : [], include_type: { @@ -1547,192 +1547,11 @@ } } - // Navigation groups for sidebar - const adminNavigationGroups = $derived([ - { - items: [ - { - id: 'general', - label: 'General', - aiId: 'workspace-settings-general', - aiDescription: 'General workspace settings' - }, - { - id: 'users', - label: 'Users', - aiId: 'workspace-settings-users', - aiDescription: 'Users workspace settings' - }, - { - id: 'ai', - label: 'Windmill AI', - aiId: 'workspace-settings-ai', - aiDescription: 'Windmill AI workspace settings' - }, - { - id: 'premium', - label: 'Premium plans', - aiId: 'workspace-settings-premium', - aiDescription: 'Premium plans workspace settings', - showIf: isCloudHosted() - } - ] - }, - { - title: 'Git & deployment', - items: [ - { - id: 'git_sync', - label: 'Git sync', - aiId: 'workspace-settings-git-sync', - aiDescription: 'Git sync workspace settings', - isEE: true - }, - { - id: 'dev_workspace', - label: 'Dev workspace', - aiId: 'workspace-settings-dev-workspace', - aiDescription: - 'Pair this workspace with a dev workspace (same code, different environment), and choose which items its deploy UI may promote' - }, - { - id: 'rulesets', - label: 'Rulesets', - aiId: 'workspace-settings-rulesets', - aiDescription: 'Protection Rulesets workspace settings', - isEE: true - } - ] - }, - { - title: 'Integrations', - items: [ - { - id: 'slack', - label: 'Slack / Teams', - aiId: 'workspace-settings-slack', - aiDescription: 'Slack / Teams workspace settings', - showIf: WORKSPACE_SHOW_SLACK_CMD - }, - { - id: 'webhook', - label: 'Webhook', - aiId: 'workspace-settings-webhook', - aiDescription: 'Webhook workspace settings', - showIf: WORKSPACE_SHOW_WEBHOOK_CLI_SYNC && !isCloudHosted() - }, - { - id: 'native_triggers', - label: 'Integration triggers', - aiId: 'workspace-settings-integrations', - aiDescription: 'Workspace integrations for integration triggers' - } - ] - }, - { - title: 'Hooks', - items: [ - { - id: 'error_handler', - label: 'Error / success handler', - aiId: 'workspace-settings-error-handler', - aiDescription: 'Error and success handler workspace settings', - isEE: true - }, - { - id: 'variable_expiration', - label: 'Variable expiration', - aiId: 'workspace-settings-variable-expiration', - aiDescription: - 'Runnable executed when a variable value is about to expire, so the value can be rotated' - }, - { - id: 'critical_alerts', - label: 'Critical alerts', - aiId: 'workspace-settings-critical-alerts', - aiDescription: 'Critical alerts workspace settings', - isEE: true - } - ] - }, - { - title: 'Data & storage', - items: [ - { - id: 'windmill_data_tables', - label: 'Data tables', - aiId: 'workspace-settings-windmill-data-tables', - aiDescription: 'Data tables workspace settings' - }, - { - id: 'windmill_lfs', - label: 'Object storage (S3)', - aiId: 'workspace-settings-windmill-lfs', - aiDescription: 'Object Storage (S3) workspace settings' - }, - { - id: 'volume_storage', - label: 'Volumes', - aiId: 'workspace-settings-volume-storage', - aiDescription: 'Volume storage workspace settings' - }, - { - id: 'ducklake', - label: 'Ducklake', - aiId: 'workspace-settings-ducklake', - aiDescription: 'Ducklake workspace settings' - }, - { - id: 'dbt', - label: 'dbt', - aiId: 'workspace-settings-dbt', - aiDescription: 'dbt warehouses workspace settings' - } - ] - }, - { - title: 'Advanced', - items: [ - { - id: 'default_app', - label: 'Apps', - aiId: 'workspace-settings-apps', - aiDescription: 'Apps workspace settings', - isEE: true - }, - { - id: 'shared_ui', - label: 'Shared UI folder', - aiId: 'workspace-settings-shared-ui', - aiDescription: 'Shared frontend folder usable by raw apps' - }, - { - id: 'dependencies', - label: 'Dependencies', - aiId: 'workspace-settings-dependencies', - aiDescription: 'Workspace dependencies settings' - }, - { - id: 'encryption', - label: 'Encryption', - aiId: 'workspace-settings-encryption', - aiDescription: 'Encryption workspace settings' - }, - { - id: 'trashbin', - label: 'Trashbin', - aiId: 'workspace-settings-trashbin', - aiDescription: 'Trashbin for recently deleted items' - } - ] - } - ]) - // A fork's creator manages its members through the same screen, but nothing else about the // workspace is theirs to change, so they get the Members entry alone. const navigationGroups = $derived( canAdmin - ? adminNavigationGroups + ? WORKSPACE_SETTINGS_SECTION_GROUPS : [ { items: [ @@ -1764,6 +1583,70 @@ params.set('tab', id) return `?${params.toString()}` } + function sectionListHref(): string { + const params = new URLSearchParams($page.url.searchParams) + params.delete('tab') + const query = params.toString() + return query ? `?${query}` : WORKSPACE_SETTINGS_PATH + } + + // Below 768px (Tailwind `md`) the sidebar would leave a phone or a session preview a sliver for + // the settings, so the list and the section become two pages. Measured on the page's own box + // rather than the viewport: the app's sidebar takes its share of a viewport first. + let layoutWidth = $state(window.innerWidth) + type SectionEntry = { id: string; label: string; showIf?: boolean; disabled?: boolean } + const sectionGroups = $derived( + navigationGroups.map((g) => ({ + title: g.title as string | undefined, + items: (g.items as SectionEntry[]).filter((i) => i.showIf !== false) + })) + ) + const visibleSections = $derived(sectionGroups.flatMap((g) => g.items)) + const pagedLayout = $derived(layoutWidth < 768 && !showYaml && visibleSections.length > 1) + // The URL says which page is on screen, so the browser's back button returns to the list and + // a link to a section opens on it. Wide, a missing `tab` still means the default section. + const sectionOpen = $derived($page.url.searchParams.has('tab')) + // The list and the section slide between each other the way `PagedContent` pages do: the + // page arriving travels a quarter of the box and fades in, the page leaving vanishes at once + // so it never ghosts over the one arriving. `side` is where a hidden page waits. + function slidingPage(shown: boolean, side: -1 | 1): string { + const offset = shown ? '' : side < 0 ? '-translate-x-1/4' : 'translate-x-1/4' + return `absolute inset-0 motion-reduce:!transition-none ${offset} ${shown ? '' : 'opacity-0 pointer-events-none'}` + } + function slideTransition(shown: boolean): string { + return `transform 130ms ease-out, opacity ${shown ? '90ms' : '0s'} ease-out` + } + // None for a single section (a fork owner's Members): Workspace settings is admin-only, so the + // picker has no branch to list it under. + const subpages: PageHeaderSubpage[] | undefined = $derived( + visibleSections.length < 2 + ? undefined + : sectionGroups.flatMap((group) => + group.items.map((i) => ({ + label: i.label, + href: WORKSPACE_SETTINGS_PATH + tabHref(i.id), + group: group.title, + current: i.id === tab, + disabled: i.disabled + })) + ) + ) + const headerSection: PageHeaderSection | undefined = $derived( + showYaml + ? { parent: 'Workspace settings', label: 'YAML' } + : pagedLayout + ? sectionOpen && tabLabel + ? { + parent: 'Workspace settings', + parentHref: sectionListHref(), + label: tabLabel, + subpages + } + : undefined + : tabLabel + ? { parent: 'Workspace settings', label: tabLabel, subpages } + : undefined + ) @@ -1774,37 +1657,77 @@ two controls that sat beside the title are the page's actions. The panes below scroll inside themselves, so the bar keeps its edge at rest rather than only under a scroll. --> -
- - - {#if !showYaml} -
- goto(tabHref(id))} - itemHref={tabHref} - /> +
+ +
+ {#if !showYaml} + +
+ + goto(tabHref(id))} + itemHref={tabHref} + drillIn={pagedLayout} + /> +
+ {/if} +
+ {@render sectionPane()}
- {/if} +
+
- -
-
-
+ {#snippet sectionPane()} +
+ {#if pagedLayout} +
+ +
+ {/if} +
+
{#if !loadedSettings} {:else if showYaml} @@ -2216,7 +2139,7 @@ documentation for more information.

{/if} -
+
-
+ {/snippet} {:else} diff --git a/frontend/src/routes/(styled)/kitchen_sink/+page.svelte b/frontend/src/routes/(styled)/kitchen_sink/+page.svelte index e21f9da550..2431c719dc 100644 --- a/frontend/src/routes/(styled)/kitchen_sink/+page.svelte +++ b/frontend/src/routes/(styled)/kitchen_sink/+page.svelte @@ -280,12 +280,14 @@ That's the full round-trip.`
- The three markdownProse presets, same source. Each is sized for its own - surface: xs for group notes and chat reasoning, sm for chat - bubbles, sticky notes and markdown job results, doc for artifacts. + The two markdownProse presets, same source. Each is sized for its own surface: + xs + for group notes and chat reasoning, sm for chat bubbles, sticky notes and + markdown job results. Artifacts use their own document stylesheet, shown on + /kitchen_sink/artifacts.
-
- {#each ['xs', 'sm', 'doc'] as const as prose} +
+ {#each ['xs', 'sm'] as const as prose (prose)}
{prose}
diff --git a/frontend/src/routes/(styled)/kitchen_sink/artifacts/+page.svelte b/frontend/src/routes/(styled)/kitchen_sink/artifacts/+page.svelte new file mode 100644 index 0000000000..789f7b7c64 --- /dev/null +++ b/frontend/src/routes/(styled)/kitchen_sink/artifacts/+page.svelte @@ -0,0 +1,415 @@ + + + + {#each pageFontLinks as href (href)} + + {/each} + + +{#snippet field(label: string)} + {label} +{/snippet} + +{#if enabled} +
+